【问题标题】:How to : bind ngModel to a property's value in Angular如何:将 ngModel 绑定到 Angular 中的属性值
【发布时间】:2018-03-20 03:50:15
【问题描述】:

我想将 ngModel 设置为如下所示的属性值

//下面的代码只是为了说明我想要实现的目标

@Component({
    selector: 'app',
    template: '<input [ngModel]="question.model" />'
})
export class Test{
     @Input() bind : {to : {me : 'hello' }}
     question = {model : 'bind.to.me'}
}

生成的模板应该是这样的

<input [ngModel]="bind.to.me" />

【问题讨论】:

    标签: angular angular2-template angular4-forms


    【解决方案1】:
    @Input() bind : {to : {me : 'hello' }};
    

    应该是

    @Input() bind = {to : {me : 'hello' }};
    

    否则,您只需指定属性的类型为{to : {me : 'hello' }} 而不是值。

    【讨论】:

    • bind 是一个输入,因此理想情况下来自父组件,将 bind 视为来自父组件的输入的占位符
    • 我认为这是不可能的。 [ngModel]="bind[question.model[first]][question.model[second]]" 和 {model : {first : 'to'}, { second: 'me'}} 应该可以工作。您需要提前知道深度,或者您使用辅助方法,该方法使用let props = bind.to.me.split('.');,然后遍历bind 以获取值,将值分配给一个字段,然后ngModel 绑定到该字段。跨度>
    猜你喜欢
    • 1970-01-01
    • 2017-07-19
    • 2017-05-09
    • 2019-10-12
    • 2019-10-24
    • 2018-12-17
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    相关资源
    最近更新 更多