如何向作用于组件的Angular指令传递Input输入值
问题原因
你的代码不生效核心是踩了Angular两个执行规则的坑:
- 输入属性赋值时机晚于构造函数执行:Angular实例化指令、组件的流程是先执行构造函数创建实例,之后再完成模板中输入属性的绑定赋值。你在构造函数里读取
this.myCustomFormat时,绑定流程还没执行,这个值永远是undefined,自然没法正确赋值给组件的format属性。 - 注意点:如果同selector的组件、指令存在同名输入,绑定值会同时传给两者,如果你不希望出现这种隐式共享,可以给指令输入加前缀或者用模板变量明确绑定归属,避免歧义。
修正方法
核心调整是把读取输入、修改组件实例的逻辑从构造函数移到ngOnInit生命周期钩子里,这个钩子触发时,所有输入属性的绑定已经全部完成。
修正后的指令代码
import { Directive, Input, OnInit } from '@angular/core'; import { ComponentAComponent } from './component-a.component'; @Directive({ selector: 'component-a', exportAs: 'componentADir' // 可选,用于模板中明确引用指令实例 }) export class ComponentADirective implements OnInit { @Input() myCustomFormat: string; constructor(private cmp: ComponentAComponent) {} ngOnInit(): void { // 此时输入属性已经完成绑定,可以正确拿到传入值 this.cmp.format = this.myCustomFormat; } }
模板使用
常规场景直接按你原来的写法绑定即可,Angular会自动把匹配到的输入值传给声明了对应@Input的指令:
<component-a [myCustomFormat]="'Test'"></component-a>
如果存在同名输入需要明确绑定归属,可以通过模板变量指定指令实例:
<component-a [myCustomFormat]="'Test'" #dir="componentADir"></component-a>
如果你希望只有传了myCustomFormat属性的时候指令才生效,还可以把指令的selector改成'component-a[myCustomFormat]',语义更清晰。
内容的提问来源于stack exchange,提问作者Haezer
相关产品推荐
相关产品推荐

