【问题标题】:how to apply ngModel to an input field using Angular如何使用 Angular 将 ngModel 应用于输入字段
【发布时间】:2020-06-30 07:56:13
【问题描述】:

大家好,我是 Angular 的新手,据我所知 ngModel 是用于双向绑定的吗?所以如果我有 2 个输入框,我可以将一个绑定到另一个,所以当我同时在其中一个上输入内容时第一个什么时候更新?

        <form >
    <div>
    <input type="text" [(ngModel)]="test" id="test1" >
    <input type="text" id="test" ">
    </div>
    </form>

我希望当我在第二个输入框上写东西时,第一个输入框显示它

【问题讨论】:

    标签: angular ngmodel


    【解决方案1】:

    当然可以。只需在输入中使用相同的ngModel。 像这样:

    <input type="text" [(ngModel)]="test" id="test1" >
    <input type="text" [(ngModel)]="test" id="test2" >
    

    【讨论】:

    • name 属性呢?因为我现在出错了
    • - 这里没有错误
    • 如果在表单标签中使用 ngModel,则必须设置 name 属性,或者必须在 ngModelOptions 中将表单控件定义为“独立”。
    • 如果使用 ngForm,所有具有 [(ngModel)]="" 的输入字段必须有一个带值的属性名称。
    【解决方案2】:

    尽管 Tony Marko 已经回答了你的问题,但还是发生了。我想补充几个细节。首先,可以在不同的情况下使用 ngModel。例如

    第一。在输入端初始化 FormControl 实例

    // Creates FormControl with a name firstName and template ref firstName
    // So FormControl props can be used in your template
    // for example *ngIf="firstName.valid"
    <input ngModel name="firstName" #firstName="ngModel">
    

    第二。一种方式值绑定

    // Value of the input changes as soon as IMMUTABLE component property changes
    <input [ngModel]="firstName" name="firstName">
    

    第三。双向绑定

    // The same as before but also changes property on input change
    <input [(ngModel)]="firstName" name="firstName">
    

    第四。分开的双向绑定

    // Its 100% identical as previous, but event emitter is separated
    // Which allows you to do side action onModelChange event
    <input [ngModel]="firstName" (ngModelChange)="firstName = $event" name="firstName">
    

    我希望它能澄清你的答案

    【讨论】:

    • 是的,这非常棒,因为不清楚为什么我需要 ID 和姓名,现在我想我明白了
    • 好。你可以删除 name 属性,Angular 会通知你它丢失了。
    猜你喜欢
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多