简体   繁体   English

具有多个输入的双向绑定

[英]Two-way binding with mutliple inputs

I'm a beginner in Angular (I'm doing Angular 2, not Angular.js), and was trying to write something that would take two inputs and do something with them without any button-click (like two-way binding).我是 Angular 的初学者(我在做 Angular 2,而不是 Angular.js),并试图编写一些可以接受两个输入并在没有任何按钮单击的情况下对它们执行某些操作(例如双向绑定)的东西。 For example, if I have two text inputs, I would like for another component (let's say a label) to contain both strings concatenated.例如,如果我有两个文本输入,我希望另一个组件(比如一个标签)包含连接的两个字符串。 Is there a way to do this?有没有办法做到这一点?

Your basic template would look something like你的基本模板看起来像

    <input type="text" [(ngModel)]="first">
    <input type="text" [(ngModel)]="second">
    <label>{{first}} {{second}}</label>

This template is using two-way data binding using ngModel directive此模板使用ngModel指令使用双向数据绑定

Sure, it is possible.当然,这是可能的。 First, you have to get user input, like this:首先,您必须获得用户输入,如下所示:

@Component({
  selector: 'app-key-up2',
  template: `
    <input #box (keyup)="onKeyInput1(box.value)">
    <input #box (keyup)="onKeyInput2(box.value)">
    <p>{{input1}}{{input2}}</p>
  `
})
export class KeyUpComponent_v2 {
  input2 = ''
  input1 = '';
  onKeyInput1(value: string) {
    this.input1 = value
  }
 onKeyInput2(value: string) {
    this.input2 = value
  }
}

Then, just show the output inside your chosen tag, like so {{ }} .然后,只需在您选择的标签内显示输出,就像{{ }}
Reference: https://angular.io/guide/user-input参考: https : //angular.io/guide/user-input

EDIT: Oh, right, you could also use [(ng-model)] , see the above answer.编辑:哦,对了,您也可以使用[(ng-model)] ,请参阅上面的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM