简体   繁体   中英

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

@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:

  1. Define a shouldAddClass property in your ChildComponent and decorate it with an @Input decorator.
  2. Use [ngClass] or [class.md-show] in your ChildComponent Template to add the class to your HTML Element depending on the value of shouldAddClass
  3. In your ParentComponent, create a property named wasParentLoaded of type boolean and set it to false initially.
  4. In your ParentComponent template, use the bind wasParentLoaded with the ChildComponent's shouldAddClass @Input property via Property Binding Syntax.
  5. When the Parent Component is Loaded, it's AfterViewInit lifecycle hook will get triggered. So inside 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM