を使用して別のコンポーネントのElementRefにアクセスすることが、未@ViewChild
import { Component, ViewChild, ElementRef, AfterViewInit} from '@angular/core';
import { HeaderComponent } from '../app/components/header/header.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent implements AfterViewInit {
title = 'app';
@ViewChild('myHeader') myHeader: ElementRef;
ngAfterViewInit() {
this.myHeader.nativeElement.style.backgroundColor = 'red';
}
}
親HTML(app.component.html)
<div>
<app-header></app-header>
</div>
今の子供HeaderComponentは以下の通りです:
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.less']
})
export class HeaderComponent implements OnInit {
constructor() {
}
ngOnInit() {
}
}
ヘッダーHTML(header.component.html)(子供)ngAfterViewInit機能this.myHeader.nativeElementで
<div #myHeader> hello</div>
はエラーを与えています。
AppComponent_Host.html:1 ERROR TypeError: Cannot read property 'nativeElement' of undefined
at AppComponent.webpackJsonp.../../../../../src/app/app.component.ts.AppComponent.ngAfterViewInit (app.component.ts:12)
at callProviderLifecycles (core.es5.js:11189)
at callElementProvidersLifecycles (core.es5.js:11164)
at callLifecycleHooksChildrenFirst (core.es5.js:11148)
at checkAndUpdateView ....
が、私はその下のように働く親HTML(app.component.html)で定義されているすべての子にアクセスしようとしたとき:
<div #myHeader> <app-header></app-header></div>
しかし、私はheader.component内の任意のElementRefにアクセスしたいです。 html.I View Encapsulationも以下のように疲れました。
encapsulation: ViewEncapsulation.None,
in HeaderComponentしかし、それも動作していません。私にここで何が欠けているか教えてください。
希望この回答は役に立ちhttps://stackoverflow.com/a/39909203/7491209 – Rajez