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

半世苍凉 提交于 2019-11-30 05:32:40

问题


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 is how my component looks like:

import { Component, Input } from "@angular/core";

import "./loadingSpinner.component.css!";

    @Component({
        selector: "loading-spinner",
        template: `
            <div *ngIf="showSpinner" class="loader-directive-wrapper">
                <div class="loader"></div>
            </div>`
    })
    export class LoadingSpinnerComponent {
        @Input() public showSpinner: boolean = false;
    } 

回答1:


constructor(elementRef:ElementRef) {
  elementRef.nativeElement.parentElement....
}



回答2:


In your child component pass parent in constructor:

  constructor(
    private parent: ParentComponent,
    ...
  )

  ngAfterViewInit() {
    console.log(this.parent);
  }



回答3:


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.




回答4:


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>


来源:https://stackoverflow.com/questions/41273384/how-to-get-the-parent-dom-element-reference-of-an-angular2-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!