此类指令:
export class SuchDirective {
title = "SuchDirectiveTitle"
...
}
此类组件导入此类指令:
@Component({
directives: [SuchDirective]
})
export class SuchComponent {
title = "OverriddenDirectiveTitle" // not working
}
如何解决这个问题?
答案 0 :(得分:3)
您可以使用SuchDirective
装饰器向@Input
添加参数:
@Directive({
selector: '[suchDirective]'
})
export class SuchDirective {
@Input('suchDirective') title: string;
...
}
然后将标题发送参数更改为:
@Component({
directives: [SuchDirective],
template: `
...
<div [suchDirective]="'some str'">this one uses the string 'some str' as title</div>
...
<div [suchDirective]="title">this one uses the SuchComponent's title property</div>
...
`
})
export class SuchComponent {
title = "OverriddenDirectiveTitle"
}
根据评论,如果SuchDirective
是@Component
并且有一个模板:
@Component({
selector: 'such-directive',
template: `This is my title {{ title }}`
})
export class SuchDirective {
@Input() title: string;
}
并使用它:
@Component({
directives: [SuchDirective],
template: `
...
Passing a fixed string as title:
<such-directive title="some str"></such-directive>
...
This one uses the SuchComponent's title property:
<such-directive [title]="title"></such-directive>
...
`
})
export class SuchComponent {
title = "OverriddenDirectiveTitle"
}