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
@viewchild decorator
or
document.querySelector()
If you have just one component
inside popup component. You can use the function ngAfterViewInit
inside popup component. Very simple :)
A better approach than using @ViewChild
would be:
shouldAddClass
property in your ChildComponent and decorate it with an @Input
decorator. [ngClass]
or [class.md-show]
in your ChildComponent Template to add the class to your HTML Element depending on the value of shouldAddClass
wasParentLoaded
of type boolean and set it to false
initially. wasParentLoaded
with the ChildComponent's shouldAddClass
@Input
property via Property Binding Syntax. ngAfterViewInit
of the ParentComponent, you can simply change wasParentLoaded
to true
. This should do the trick.
Here's a Sample StackBlitz for your ref.
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. Only in the Development Mode though.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.