有许多演示组件通信的代码示例,
我对这两种技术之间的区别感到困惑
- 子组件
- 查看 child
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之间的关系是 只有单向绑定(bind),父组件和子组件之间是双向绑定(bind)?
核心下的act、data Binding、Lifecycle如何?
真正的实际用途是什么,解决什么问题?
最佳答案
是的,其中一些术语令人困惑。
在大多数情况下,父子关系(父组件和子组件)是指在另一个组件的 HTML 中的一个组件。
在下面的示例中,“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
另一方面,装饰器允许您访问组件关联模板上的任何 元素。然后就可以直接访问了。这与父/子组件没有直接关系。
例如,您可以访问任何随机的 <div>
页面上的元素并设置其背景颜色。或者您可以访问 <input>
元素并设置其焦点。
希望这有助于澄清差异。
关于angular - ViewChild 与 ChildComponent - Angular 6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51535670/