[]和{{}}之间的区别在于将状态绑定到属性吗? [英] Difference between [] and {{}} for binding state to property?

查看:48
本文介绍了[]和{{}}之间的区别在于将状态绑定到属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个模板示例:

<span count="{{currentCount}}"></span>
<span [count]="currentCount"></span>

这两个人都做同样的事情.哪个是首选,为什么?

Here both of them does the same thing. Which one is preferred and why?

推荐答案

[]用于将父组件中的值绑定到子组件中的@Input().它允许传递对象.

[] is for binding from a value in the parent component to an @Input() in the child component. It allows to pass objects.

{{}}用于在属性和HTML之类的

{{}} is for binding strings in properties and HTML like

<div somePropOrAttr="{{xxx}}">abc {{xxx}} yz</div>

其中绑定可以是字符串的一部分.

where the binding can be part of a string.

()用于绑定触发DOM事件或子组件上的EventEmitter发出事件时要调用的事件处理程序

() is for binding an event handler to be called when a DOM event is fired or an EventEmitter on the child component emits an event

@Component({
    selector: 'child-comp',
    template: `
    <h1>{{title}}</h1>
    <button (click)="notifyParent()">notify</button>
    `,
})
export class ChildComponent {
  @Output() notify = new EventEmitter();
  @Input() title;

  notifyParent() {
    this.notify.emit('Some notification');
  }
}


@Component({
    selector: 'my-app',
    directives: [ChildComponent]
    template: `
    <h1>Hello</h1>
    <child-comp [title]="childTitle" (notify)="onNotification($event)"></child-comp>
    <div>note from child: {{notification}}</div>
    `,
})
export class AppComponent {
  childTitle = "I'm the child";

  onNotification(event) {
    this.notification = event;
  }
}

> 柱塞示例

https://angular中的更多详细信息.io/docs/ts/latest/guide/template-syntax.html#!#binding-syntax

这篇关于[]和{{}}之间的区别在于将状态绑定到属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆