覆盖Angular2中的指令变量

时间:2016-07-28 23:50:08

标签: angular

此类指令:

export class SuchDirective {

    title = "SuchDirectiveTitle"
    ...
}

此类组件导入此类指令:

@Component({
    directives: [SuchDirective]
})

export class SuchComponent {
    title = "OverriddenDirectiveTitle" // not working
}

如何解决这个问题?

1 个答案:

答案 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"
}