[英]Angular2,How to broadcast event from parent component to child directive?
[英]Angular 9: How to get data from parent component in child directive
我有父组件,里面有子指令。 需要从指令中的组件获取输入数据。
<my-parent [data]="'Hello from parent'">
<input myChild>
</my-parent>
父组件
@Component({
selector: 'my-parent',
template: `
<ng-content select="[myChild]"></ng-content>
`
})
export class ParentComponent {
@Input() data: string;
}
儿童指令
@Directive({
selector: '[myChild]'
})
export class ChildDirective implements OnInit {
value: string;
ngOnInit() {
// needs to get data from parent component here
}
}
我可以将父组件注入指令,但我不想这样做,因为它会增加循环依赖的风险。
我可以在 ParentComponent 中使用@ContentChild
并通过公共属性在AfterContentInit
中传递数据,但我不确定此属性何时可以在 ChildDirective 中使用,我应该在这种情况下使用AfterContentChecked
吗?
父组件
@ContentChild(ChildDirective, {static: true}) child: ChildDirective;
ngAfterContentInit() {
this.child.value = this.data;
}
儿童指令
value: string;
ngAfterContentChecked() {
// will be available data from parent here?
}
也许我应该使用服务在组件和指令之间共享数据?
https://stackblitz.com/edit/angular-pass-data-to-child-directive
是否有特殊原因需要使用 ng-content 而不是 ng-template?
我建议您使用 ng-templates 的方法如下
父组件
@Component({
selector: 'my-parent',
template: `
<ng-template
[ngTemplateOutlet]="child"
[ngTemplateOutletContext]="{ $implicit: data }">
</ng-template>
`
})
export class ParentComponent implements AfterContentInit {
@Input() data: string;
@ContentChild(TemplateRef, {static: true}) child: TemplateRef<any>;
}
儿童指令
@Directive({
selector: '[myChild]'
})
export class ChildDirective {
@Input()
value: string;
}
用法
<my-parent [data]="'Hello from parent'">
<ng-template let-dataThroughParent>
<input myChild [value]="dataThroughParent" class="form-control">
</ng-template>
</my-parent>
重要的
在这种特定情况下(示例),实际上没有必要将数据绑定到您的父级,然后通过模板变量获取它,然后再次将其绑定到您的“myChild”指令,因为如果您的用例与此类似,我会将数据直接传递给“myChild”指令,如下所示:
<my-parent [data]="'Hello from parent'">
<ng-template>
<input myChild [value]="'Hello from parent'" class="form-control">
</ng-template>
</my-parent>
请注意,它也适用于您的初始方法:
<my-parent [data]="'Hello from parent'">
<input myChild [value]="'Hello from parent'">
</my-parent>
但我假设您确实需要从使用父级的 scope 中无法访问的父级传递数据。 这是一个工作示例
https://stackblitz.com/edit/angular-pass-data-to-child-directive-ebcbg6
您可以使用@Input()
绑定将数据传递给指令。
app.component.html
<my-parent [data]="'Hello from parent'"></my-parent>
我的父级组件.ts
@Component({
selector: 'my-parent',
templateUrl: './my-parent.component.html',
styleUrls: ['./my-parent.component.scss'],
})
export class MyParentComponent implements OnInit {
@Input() data: string;
}
我的父组件.html
<input [myChild]="data"/>
my-child.directive.ts
@Directive({
selector: '[myChild]'
})
export class ChildDirective implements OnInit {
value: string;
@Input('myChild') data: string;
ngOnInit() {
console.log(this.data) // data from parent
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.