【问题标题】:Access child host elements nativeElement properties from host element in angular 4从角度 4 中的宿主元素访问子宿主元素 nativeElement 属性
【发布时间】:2018-01-29 16:48:27
【问题描述】:

我想从父组件即 AppComponent 获取 mat-card 的 elementReference。我已经编写了一个指令并将其附加到主机组件。如果我尝试访问 elem.nativeElement.childNodes[0] ,它会给出未定义的。如何从父组件访问 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;
}

Card-overview-example.html

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

card-overview-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

【问题讨论】:

    标签: javascript angular angular-material2


    【解决方案1】:

    尝试elem.nativeElement.children[0] 而不是elem.nativeElement.childNodes[0]

    【讨论】:

    • 你应该使用 ViewChild 来访问指令
    • elem.nativeElement.children 没有用。仍然是未定义的
    • 关于如何使用 ViewChild 访问指令的任何链接? @大卫安东尼阿科斯塔
    • 如果我使用 viewChild@ViewChild(DisplayStyleDirective) ds : DisplayStyleDirective 和我的 ngAfterViewInit() { console.log(this.ds) }
    • 我想将样式应用于 mat-card 。我重新使用了相同的组件,在一个地方我想要添加样式,而在另一个地方我不想要。这就是为什么我想采用 elementRef 并对其应用样式。
    猜你喜欢
    • 1970-01-01
    • 2016-10-19
    • 2023-04-06
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2018-11-19
    • 2019-07-15
    相关资源
    最近更新 更多