How to get the parent DOM element reference of an angular2 component

前端 未结 5 1785
醉酒成梦
醉酒成梦 2021-01-04 20:32

I need to access to some properties of the parent DOM element which contains the component from where i want to get the info, is there a way to do such thing?

Here i

相关标签:
5条回答
  • 2021-01-04 21:12

    In your child component pass parent in constructor:

      constructor(
        private parent: ParentComponent,
        ...
      )
    
      ngAfterViewInit() {
        console.log(this.parent);
      }
    
    0 讨论(0)
  • 2021-01-04 21:13
    constructor(elementRef:ElementRef) {
      elementRef.nativeElement.parentElement....
    }
    
    0 讨论(0)
  • 2021-01-04 21:20

    The child component shouldn't update properties on the parent. Instead have the child emit events and the parent change the properties. The docs have an example in the Component Interaction section.

    0 讨论(0)
  • 2021-01-04 21:20

    for accessing values of parent you can use @input. for changing parent values try this example

    child component

    import { Component, EventEmitter, Input, Output } from '@angular/core';
    
    @Component({
      selector: 'rio-counter',
      templateUrl: 'app/counter.component.html'
    })
    export class CounterComponent {
      @Input()  count = 0;
      @Output() result = new EventEmitter<number>();
    
      increment() {
        this.count++;
        this.result.emit(this.count);
      }
    }
    

    child html part

    <div>
      <p>Count: {{ count }}</p>
      <button (click)="increment()">Increment</button>
    </div>
    

    parent component

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'rio-app',
      templateUrl: 'app/app.component.html'
    })
    export class AppComponent {
      num = 0;
      parentCount = 0;
    
      assignparentcount(val: number) {
        this.parentCount = val;
      }
    }
    

    parent html part

    <div>
      Parent Num: {{ num }}<br>
      Parent Count: {{ parentCount }}
      <rio-counter [count]="num" (result)="assignparentcount($event)">
      </rio-counter>
    </div>
    
    0 讨论(0)
  • 2021-01-04 21:35

    If you want to get data from the parent component, you may want to review data exchange methods between components. It seems to me that you may want to take a look at the Input decorator. You can do something like: <app-spinner show="true"></app-spinner> Or <app-spinner show="isBusy()"></app-spinner>

    Take a look at it here: https://angular.io/guide/inputs-outputs

    0 讨论(0)
提交回复
热议问题