[英]Parent-Child Component communication
Which is good below mentioned method for changing the child component properties from parent component? 下文提到的从父组件更改子组件属性的方法中哪一种是好的?
Task: 任务:
I want to add class 'md-show' to my pop up modal component from parent component when parent component loaded 我想在加载父组件时将类'md-show'从父组件添加到弹出模式组件中
@viewchild decorator
or 要么
document.querySelector()
If you have just one component
inside popup component. 如果你只有一个
component
弹出组件内。 You can use the function ngAfterViewInit
inside popup component. 您可以在弹出组件内部使用函数
ngAfterViewInit
。 Very simple :) 很简单 :)
A better approach than using @ViewChild
would be: 比使用
@ViewChild
更好的方法是:
shouldAddClass
property in your ChildComponent and decorate it with an @Input
decorator. shouldAddClass
属性,并使用@Input
装饰器@Input
装饰。 [ngClass]
or [class.md-show]
in your ChildComponent Template to add the class to your HTML Element depending on the value of shouldAddClass
[ngClass]
或[class.md-show]
将类添加到HTML元素中,具体取决于shouldAddClass
的值 wasParentLoaded
of type boolean and set it to false
initially. wasParentLoaded
的属性,其类型为boolean,并将其初始设置为false
。 wasParentLoaded
with the ChildComponent's shouldAddClass
@Input
property via Property Binding Syntax. wasParentLoaded
与ChildComponent的shouldAddClass
@Input
属性一起使用。 ngAfterViewInit
of the ParentComponent, you can simply change wasParentLoaded
to true
. ngAfterViewInit
内部,您可以简单地将wasParentLoaded
更改为true
。 This should do the trick. 这应该可以解决问题。
Here's a Sample StackBlitz for your ref. 这是供您参考的示例StackBlitz 。
PS: This would give you the ExpressionChangedAfterItHasBeenCheckedError
on the console since we're trying to change a property on the Component while Angular was performing its Change Detection. PS:这将在控制台上给您
ExpressionChangedAfterItHasBeenCheckedError
,因为我们试图在Angular执行其更改检测时更改Component的属性。 Only in the Development Mode though. 但是仅在开发模式下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.