我成功地<ng-content></ng-content>用来在孙子中显示一个组件,如下所示:带有客户组件的父对子组件树,但现在我想@ContentChild在那个孙子中使用来访问传入的内容,但我似乎无法得到任何工作.
这是我尝试使用选择器和@ContentChildstackBlitz:https://stackblitz.com/edit/angular-dpu4pm
.无论我做什么,@ContentChild总是在TheChild组件中未定义,但在TheParent组件中工作.
@Component({
selector: 'spinner',
template: `
spinner
`,
})
@Component({
selector: 'my-app',
template: `
works <the-parent><spinner #spin></spinner></the-parent>
`,
})
@Component({
selector: 'the-parent',
template: 'this is parent <the-child><ng-content #content></ng-content></the-child>'
})
export class TheParent implements AfterViewInit{
@ContentChild('spin') spin;
ngAfterViewInit() {
alert('parents spin is '+typeof this.spin); //object
}
}
@Component({
selector: 'the-child',
template: 'this is child <ng-content></ng-content>'
})
export class TheChild implements AfterViewInit{
@ContentChild('spin') spin;
@ContentChild('content') content;
ngAfterViewInit() { …Run Code Online (Sandbox Code Playgroud) 我在模板驱动的表单中使用ngFor添加了几个输入,我想在输入无效时添加相应的错误消息.通常,如果我没有使用ngFor,我会使用#inputName ="ngModel".为了引用动态添加的输入,我有什么方法可以做这样的事情吗?
基本上我想做这样的事情:
<div *ngFor="let field of fields; let i = index">
<label>{{field.label}}</label> <input [ngModel]="field.value" required #field{{i}}="ngModel" />
<div *ngIf="field{{i}}.invalid"> This field is required </div>
</div>
Run Code Online (Sandbox Code Playgroud)