angular中双向绑定语法糖实现

2 篇文章 0 订阅
1 篇文章 0 订阅

Abstract

在Angular中,[]用来绑定变量,()用来绑定事件,但还有一种组合形式当’[()]'出现时,表示双向绑定。

语法糖解析

<p [(customVal)]="x"></p>
// 解析后
<p [customVal]="x" (customValChange)="x = $event"></p>

case-弹窗组件

ng g c dialog

dialog.component.html:

<div class="dialog" [hidden]="!visible">
  <p>dialog works!</p>
  <button (click)="onClose()">点我关闭</button>
</div>

dialog.component.ts:

import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-dialog',
  templateUrl: './dialog.component.html',
  styleUrls: ['./dialog.component.scss'],
})
export class DialogComponent {
  @Input() visible = false;
  @Output() visibleChange = new EventEmitter<boolean>();
  onClose() {
    this.visibleChange.emit(false);
  }
}

使用弹窗组件:

demo.component.html:

<p>demo works!</p>
<button (click)="visible = true">打开弹窗</button>
<app-dialog [(visible)]="visible"></app-dialog>

demo.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.scss'],
})
export class DemoComponent {
  public visible = false;
}

效果:

点击打开能打开,点击关闭则关闭。使用方便。

扩展ngModel指令

通过引入FormsModule模块,对于原生的input,checkbox等表单元素,可以使用[(ngModel)]进行双向绑定。

app.module.ts:

import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [
        FormsModule,
    ],
})

component.html:

<input [(ngModel)]="name" />
{{name}}

component.ts:

public name = '青梅';

效果:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

Tip:ngModel内置指令的原理其实就是将表单的value和input事件结合,进行双向绑定。
想要源码的,可以来访问我的代码仓:
https://gitee.com/gao-hui007/my-blogs/blob/master/docs/angular/%E5%8F%8C%E5%90%91%E7%BB%91%E5%AE%9A.md#
转载请备注来源

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值