从angular 4中的host元素访问子主机元素nativeElement属性

时间:2018-01-29 16:48:27

标签: javascript angular angular-material2

我希望来自父组件的mat-card的elementReference,即AppComponent。我编写了一个指令并将其附加到主机组件。如果我尝试访问elem.nativeElement.childNodes [0],它会给出undefined。如何从父组件访问mat-card元素引用。

这是demo。 谢谢 这是我的指示

import { Directive, ElementRef, Renderer2 } from '@angular/core';

@Directive({ selector: '[displayStyle]' })
export class DisplayStyleDirective {
constructor(elem: ElementRef, renderer: Renderer2) {
   console.log(elem.nativeElement.childNodes[0])
   }
 }

在控制台中我得到了未定义。

App.Component.html

<div>
  <h3>Recognized Images</h3>
  <div>
    <card-overview-example displayStyle *ngFor="let user of existingUserInfo" [User]="user"></card-overview-example>
  </div> 
</div>

App.component.ts

import {
  Component,
  OnInit,
  AfterViewInit,
  ElementRef,
  Renderer2,
  ViewChild
} from "@angular/core";
@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
})
export class AppComponent implements OnInit,AfterViewInit {
  constructor(private elementRef: ElementRef,
    private renderer: Renderer2) { }
  ngOnInit() { }
existingUserInfo:Array<userDetails> = [
  {userID:"121",filename:"https://upload.wikimedia.org/wikipedia/commons/thumb/c/cf/Angular_full_color_logo.svg/250px-Angular_full_color_logo.svg.png"},
  {userID:"122",filename:"https://upload.wikimedia.org/wikipedia/commons/thumb/c/cf/Angular_full_color_logo.svg/250px-Angular_full_color_logo.svg.png"},
  {userID:"123",filename:"https://upload.wikimedia.org/wikipedia/commons/thumb/c/cf/Angular_full_color_logo.svg/250px-Angular_full_color_logo.svg.png"}
]

 ngAfterViewInit() {
  }



}

export interface userDetails {
  userID: string;
  filename: string;
}

插卡概述-example.html的

<mat-card class="example-card">
  <img [src]="userDetails.filename" alt="Photo of {{userDetails.userID}}">
  <p >{{userDetails.userID}}</p>
</mat-card>

卡概述-example.ts

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

/**
 * @title Basic cards
 */
@Component({
  selector: 'card-overview-example',
  templateUrl: 'card-overview-example.html'
})
export class CardOverviewExample {
    @Input("User") userDetails: userDetails;
}

export interface userDetails {
  userID: string;
  filename: string;
}

这是demo

1 个答案:

答案 0 :(得分:0)

尝试使用elem.nativeElement.children[0]代替elem.nativeElement.childNodes[0]