【问题标题】:How to display dynamic control within component如何在组件内显示动态控件
【发布时间】:2017-11-19 05:12:59
【问题描述】:

我正在尝试构建一个基于输入属性呈现其 html 控件的自定义组件。我遇到困难的地方是确保自定义组件上的所有指令都添加到相应的 html 控件中。也许我做错了?任何见解都会很棒。

<custom-attribute [type]="'dropdown'" [style.display]="'block'" [(ngModel)]="message">

@Component({
  selector: 'custom-attribute',
  template: 
    `
    <input type="text" *ngIf="type === 'text'">
    <select *ngIf="type === 'dropdown'">
    `
})
export class CustomAttribute {
  @Input("type") type: string;
}

【问题讨论】:

  • 我在您的代码中没有发现任何问题。这里有什么问题?
  • 例如双向绑定不起作用。 ngModel 指令放置在自定义属性而不是输入控件上。

标签: angular angular2-directives angular2-components


【解决方案1】:

试试这个:

<custom-attribute [type]="'dropdown'" [style.display]="'block'" [(message)]="message">

@Component({
    selector: 'custom-attribute',
    template: 
    `
        <input [(ngModel)]="message" type="text" *ngIf="type === 'text'">
        <select *ngIf="type === 'dropdown'">
    `
     })

    export class CustomAttribute {
      @Input("type") type: string;
      @Input('message') model:any;
    }

【讨论】:

  • 绑定不起作用。输入控件为空
  • 似乎您只需传递一个对象就可以解决它。如果使用原始类型,双向绑定将不起作用。
  • 是的,你是对的。两种方式绑定仅适用于对象(据我所知)。
猜你喜欢
  • 1970-01-01
  • 2012-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
  • 2013-02-12
  • 2019-07-26
相关资源
最近更新 更多