ViewChild 与 ChildComponent - Angular 6
ViewChild vs ChildComponent - Angular 6
有很多演示组件通信的代码示例,
我对这两种技术之间的区别感到困惑
- 子组件
- ViewChild
ViewChild 已定义:
ViewChild decorator get access to a child component, directive or a
DOM element from a parent component class, ViewChild returns the first
element that matches a given component, directive or template
reference selector.
根据这个参考,
ViewChild 授予 DOM 元素对父组件的完全访问权限,指令无需在任何更新时将 EventEmitter 发送到父组件。
我的问题
- 我们可以说父组件和viewchild之间的关系是
只有单向绑定,父组件和子组件之间是2向绑定?
core下的act,data Binding,Lifecycle如何?
真正的实际用途是什么,解决什么问题?
Component interactions 是两个组件相互通信的方式。
ViewChild decorator 是现有的组件交互之一。
是的,有些术语令人困惑。
在大多数情况下,父子关系(父组件和子组件)指的是另一个组件的HTMLHTML中的一个组件。
在下面的示例中,"star" 组件是产品详细信息组件中的子组件。
子组件直接添加到父组件的模板中:
父模板:
<div class='col-md-8'>
<pm-star [rating]='product.starRating'>
</pm-star>
</div>
子组件
@Component({
selector: 'pm-star',
templateUrl: './star.component.html',
styleUrls: ['./star.component.css']
})
export class StarComponent {
// ...
}
另一方面,ViewChild
装饰器允许您访问组件关联模板上的 any 元素。然后就可以直接访问了。这与 parent/child 个组件没有直接关系。
例如,您可以访问页面上的任何随机 <div>
元素并设置其背景颜色。或者您可以访问 <input>
元素并设置其焦点。
希望这有助于澄清差异。
有很多演示组件通信的代码示例,
我对这两种技术之间的区别感到困惑
- 子组件
- ViewChild
ViewChild 已定义:
ViewChild decorator get access to a child component, directive or a DOM element from a parent component class, ViewChild returns the first element that matches a given component, directive or template reference selector.
根据这个参考,
ViewChild 授予 DOM 元素对父组件的完全访问权限,指令无需在任何更新时将 EventEmitter 发送到父组件。
我的问题
- 我们可以说父组件和viewchild之间的关系是 只有单向绑定,父组件和子组件之间是2向绑定?
core下的act,data Binding,Lifecycle如何?
真正的实际用途是什么,解决什么问题?
Component interactions 是两个组件相互通信的方式。
ViewChild decorator 是现有的组件交互之一。
是的,有些术语令人困惑。
在大多数情况下,父子关系(父组件和子组件)指的是另一个组件的HTMLHTML中的一个组件。
在下面的示例中,"star" 组件是产品详细信息组件中的子组件。
子组件直接添加到父组件的模板中:
父模板:
<div class='col-md-8'>
<pm-star [rating]='product.starRating'>
</pm-star>
</div>
子组件
@Component({
selector: 'pm-star',
templateUrl: './star.component.html',
styleUrls: ['./star.component.css']
})
export class StarComponent {
// ...
}
另一方面,ViewChild
装饰器允许您访问组件关联模板上的 any 元素。然后就可以直接访问了。这与 parent/child 个组件没有直接关系。
例如,您可以访问页面上的任何随机 <div>
元素并设置其背景颜色。或者您可以访问 <input>
元素并设置其焦点。
希望这有助于澄清差异。