我想创建一个“我的表单组”组件,它由一个标签、任何类型的输入元素(输入、复选框等)和一个用于验证结果的 div 组成。 我想使用内容投影在标签后插入输入。像这样:
<form [ngFormModel]="myForm" (ngSubmit)="onSubmit()">
<my-form-group>
<input type="text"
class="form-control"
[ngFormControl]="myForm.controls['name']">
</my-form-group>
<form>
组件可能如下所示:
@Component({
selector: 'my-form-group',
template: `
<div class="form-group">
<label for="name">Name<span [ngIf]="name.required"> *</span></label>
<ng-content></ng-content>
<div [hidden]="name.valid || name.pristine" class="alert alert-danger">
Please check your input
</div>
</div>`
})
...
我想使用投影组件的状态来隐藏或显示“必需”星号和验证 div。据我所知,可以使用 @ContentChild()
和 ngAfterContentInit()
访问投影组件,但我认为,我必须有一个特殊的组件才能使用这个。
如果我不知道确切的组件,访问投影组件的 Controller 的最佳方式是什么?
最佳答案
您可以使用 @ContentChild()
您需要在其中传递模板变量的名称或组件或指令的类型。
模板变量的缺点是,您的组件的用户需要使用正确的名称来应用它,这使得您的组件更难使用。
对于父组件(使用<my-form-group>
)需要添加providers: [MyProjectionDirective]
的组件或指令类似这同样很麻烦。
第二种方法允许变通
provide(PLATFORM_DIRECTIVES, {useValue: [MyProjectionDirective], multi: true})
什么时候MyProjectionDirective
有一个与投影内容匹配的选择器(如 selector: 'input'
),然后该指令将应用于每个输入元素,您可以查询它。缺点是,该指令随后还会应用于 Angular 应用程序中的任何其他输入元素。
您也没有得到投影组件的组件实例,而是指令。你可以告诉@ContentChild()
获取组件实例,但为此您需要提前知道类型。
因此,模板变量的方法似乎是最好的选择:
使用模板变量的例子
@Component({
selector: 'my-input',
template: `
<h1>input</h1>
<input>
`,
})
export class InputComponent {
}
@Component({
selector: 'parent-comp',
template: `
<h1>Parent</h1>
<ng-content></ng-content>
`,
})
export class ParentComponent {
@ContentChild('input') input;
ngAfterViewInit() {
console.log(this.input);
// prints `InputComponent {}`
}
}
@Component({
selector: 'my-app',
directives: [ParentComponent, InputComponent],
template: `
<h1>Hello</h1>
<parent-comp><my-input #input></my-input></parent-comp>
`,
})
export class AppComponent {
}
关于angular - 在angular2中访问任意 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36881692/