【问题标题】:Angular2 pass outer attributes to inner contentsAngular2将外部属性传递给内部内容
【发布时间】:2016-08-26 16:36:19
【问题描述】:

我有一个自定义指令如下

@Component({
  selector: 'my-textfield' ,
  template: `
    <div>
      <label floating>{{label}}</label>
      <input type="text"></input>
    </div>
  `,
})
export class TextFieldInput{
    @Input label:string;
}

如何实现以下目标,将[(ngModel)] 等属性传递到自定义指令的输入文本字段?

<my-textfield label="Name" [(ngModel)]="user.name" ></my-textfield>

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

    添加一个

    [(ngModel)]="whatever"
    

    到您的自定义指令的输入字段,就像这样:

    @Component({
      selector: 'my-textfield' ,
      template: `
        <div>
          <label floating>{{label}}</label>
          <input [(ngModel)]="whatever" type="text"></input>
        </div>
      `,
    })
    
    export class TextFieldInput{
        @Input label:string;
        @Input whatever:string
    }
    

    并在父组件中用作

    <my-textfield label="Name" [whatever]="user.name" ></my-textfield>
    

    这并不完全是您的问题所暗示的,但对于您提供的示例,它具有相同的效果。为自定义指令实现 ngModel 逻辑要复杂得多。

    【讨论】:

    • 谢谢。但我已经尝试过了。这不会完全起作用,因为 2-way 绑定不适用于自定义组件
    • 那么,你的答案就在这篇文章中:almerosteyn.com/2016/04/… 它还包括一个检查器。
    猜你喜欢
    • 1970-01-01
    • 2017-04-22
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 2013-11-07
    • 1970-01-01
    相关资源
    最近更新 更多