【问题标题】:Override Directive Variable in Angular2覆盖Angular2中的指令变量
【发布时间】:2016-07-28 23:50:08
【问题描述】:

这样的指令:

export class SuchDirective {

    title = "SuchDirectiveTitle"
    ...
}

导入此类指令的此类组件:

@Component({
    directives: [SuchDirective]
})

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

如何解决这样的问题?

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以使用@Input 装饰器向SuchDirective 添加参数:

    @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"
    }
    

    更新:

    每个 cmets,如果 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"
    }
    

    【讨论】:

    • 谢谢!但是,如果指令提供模板(也就是您可能知道的指令的组件)会怎样
    • 额外问题:如果我在指令模板中定义一个函数调用会怎样:&lt;such-directive [title]="title" (click)="suchDirective.next()。我使用 ViewChild 导入了指令,但不知何故我无法弄清楚,在调试工具中得到“无法读取未定义的属性”。
    • 我不太明白你在说什么(也许用细节创建一个新问题是个好主意),但是当你写 &lt;such-directive [title]="title" (click)="suchDirective.next() 时,你是在告诉 SuchDirective 有名称为 click@Output()/output,它在触发时计算表达式 suchDirective.next()。但是SuchComponent 处没有suchDirective 变量(such-directive 指令的使用不会自动创建一个...)
    • 您的评论为我指明了正确的方向。再次感谢! toddmotto.com/component-events-event-emitter-output-angular-2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    • 2016-11-08
    • 2017-04-19
    • 1970-01-01
    • 2021-06-29
    相关资源
    最近更新 更多