Home > Web Front-end > JS Tutorial > Take you to understand two-way binding in Angular10

Take you to understand two-way binding in Angular10

青灯夜游
Release: 2021-09-15 10:48:25
forward
2410 people have browsed it

The following article will take you through two-way binding and take a look at the two types of two-way binding in Angular. I hope it will be helpful to everyone!

Take you to understand two-way binding in Angular10

We have learned about property binding, event binding, and the use of input and output. It is time to learn about two-way binding. In this section, we will use @Input() and @Output() to learn about two-way binding. [Related tutorial recommendations: "angular tutorial"]

Definition: Two-way binding provides a way for components in the application to share data. Use two-way binding to listen to events and update values ​​synchronously between parent and child components. (In fact, it is a simplification of @Input() and @Output())

Two-way binding can be roughly divided into two types :

1. Two-way binding of ordinary components

This type of two-way binding can occur in any component## On the #DOM element, let’s take a closer look at it through an example.

Create a

sizer component as a subcomponent below src/app/components/:

// src/app/components/sizer/sizer.component.html
<div>
  <button class="btn btn-danger" (click)="dec()" title="smaller">-</button>
  <button class="btn btn-primary" (click)="inc()" title="bigger">+</button>
  <label [style.font-size.px]="size">FontSize: {{size}}px</label>
</div>
// src/app/components/sizer/sizer.component.ts
...
export class SizerComponent implements OnInit {
  public size = 14;
  // ...
  dec() {
    this.size++;
  }
  inc() {
    this.size--;
  }
}
Copy after login

The page will look like this, and the button function is implemented :

Take you to understand two-way binding in Angular10

However, this is not the result we want. We need to

pass in size from the parent component so that The sizer component changes the font size. And, through the button click event of the sizer component, the changed value of size is passed back to the parent component.

Next we will use the previous knowledge to transform the code (

That is, an introduction to the principle of two-way binding):

// src/app/app.component.html
// 下面的$event就是子组件传过来的值(必须是$event)
<app-sizer [size]="appFontSize" (onSizeChange)="appFontSize = $event"></app-sizer>
<div [style.font-size.px]="appFontSize">子组件修改后的FontSize: {{appFontSize}}</div>

// src/app/app.component.ts
...
export class AppComponent {
  appFontSize = 14;
}
Copy after login
rrree

also achieves what we want Effect:

Take you to understand two-way binding in Angular10 However, isn’t this too much trouble? Next, our two-way binding officially appears:

Angular’s ​​two-way binding syntax is a combination of square brackets and round brackets

[()]. [] performs attribute binding, () performs event binding. Modify the following code:

// src/app/components/sizer/sizer.component.ts
...
export class SizerComponent implements OnInit {
  // 创建输入属性size,为number或字符串类型
  @Input() size: number | string;
  // 创建自定义事件onSizeChange,需要一个number类型的参数
  @Output() onSizeChange = new EventEmitter<number>();
  ....
  dec() {
    this.resize(-1);
  }
  inc() {
    this.resize(1);
  }
  resize(step: number) {
    // 设置字体大小为12~40之间的值
    this.size = Math.min(40, Math.max(12, +this.size + step));
    // 通过事件传值
    this.onSizeChange.emit(this.size);
  }
}
Copy after login
// src/app/app.component.html
<app-sizer [(size)]="appFontSize"></app-sizer>
<div [style.font-size.px]="appFontSize">子组件修改后的FontSize: {{appFontSize}}</div>
Copy after login

and you will find that the function is not affected.

2. Two-way binding in the form [(ngModel)]

Based on the previous basic two-way binding Knowledge, [(ngModel)] The syntax can be broken down into:

1.

Input attribute named ngModel

2.

Output attribute named ngModelChange

Use the form element alone

First you need to introduce

FormsModuleThis built-in module:

// src/app/components/sizer/sizer.component.ts
...
export class SizerComponent implements OnInit {
  @Input() size: number | string;
  // 修改事件名,********必须是:属性名 + Change 形式*********
  @Output() sizeChange = new EventEmitter<number>();
  ....
  resize(step: number) {
    this.size = Math.min(40, Math.max(12, +this.size + step));
    this.sizeChange.emit(this.size);
  }
}
Copy after login

Used in the component:

// src/app/app.module.ts 
import {FormsModule} from &#39;@angular/forms&#39;;
...
@NgModule({
  // ...
  imports: [
    // ...
    FormsModule
  ],
  // ...
})
Copy after login

The above line of code is equivalent to:

<!-- src/app/app.component.html -->
<input type="text" [(ngModel)]="iptVal">
<p>input value is {{iptVal}}</p>
Copy after login

This is actually very simple, similar to the writing method in vue.

Use

in the tag and put the code inside the

tag:
<input [value]="iptVal" (input)="iptVal = $event.target.value" />
Copy after login

However, we will find that the browser will report an error:

Take you to understand two-way binding in Angular10 The error message means that using
ngModel# in the form form ##, we need to add a name attribute to input or set [ngModelOptions]="{standalone: ​​true}"Modify Code:

<!-- src/app/app.component.html -->
<form>
  <input type="text" [(ngModel)]="iptVal2">
  <p>form 中input value is {{iptVal2}}</p>
</form>
Copy after login

or:

<!-- src/app/app.component.html -->
<form>
  <input type="text" [(ngModel)]="iptVal2" name="appIput2">
  <p>form 中input value is {{iptVal2}}</p>
</form>
Copy after login

or:

<!-- src/app/app.component.html -->
<form>
  <input type="text" [(ngModel)]="iptVal2" [ngModelOptions]="{standalone: true}">
  <p>form 中input value is {{iptVal2}}</p>
</form>
Copy after login

It’s so simple to use two-way binding in form elements, pay attention to introducing the

FormsModule

module That’s it.

Summary:

1. The principle of two-way binding is actually @Input() and @ Output() When used in combination, please note that the syntax is [(property name)] = "a property name in the parent component", bind the input first, and then bind the output;

2. To use two-way binding in the form form, you should first introduce the FormsModule built-in module, and then add it to the input element name. For more programming-related knowledge, please visit:

Programming Learning

! !

The above is the detailed content of Take you to understand two-way binding in Angular10. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template