我可以在Angular2的指令中访问子元素吗? [英] Can I access child elements within a directive in Angular2?

查看:56
本文介绍了我可以在Angular2的指令中访问子元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个指令,该指令在输入中接受 icon 属性,该属性将是图标名称.因此,该指令将在内部尝试找到将在其中应用类的 span 元素.我想知道是否可以从应用于父级的指令中做到这一点.还是我也必须为孩子创建指令?

I'm trying to create a directive that accepts in input a icon property which would be the icon name. So the directive internally would try to find a span element where it will apply a class. I wonder if this is possible from within the directive applied to the parent. Or do I have to create a directive for the child too?

这是我的HTML代码:

Here's my HTML code:

<div sfw-navbar-square sfw-navbar-icon>
  <span class="mdi mdi-magnify"></span>
</div>

这是指令本身:

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

@Directive({
  selector: '[sfw-navbar-square]'
})
export class NavbarSquareDirective {

  // Here I'd like to define a input prop that takes a string    
  constructor(private el: ElementRef, private renderer: Renderer) {
    this.renderer.setElementClass(this.el.nativeElement, 'navbar-square-item', true);
    this.renderer.setElementClass(this.el.nativeElement, 'pointer', true);
    this.renderer.setElementClass(this.el.nativeElement, 'met-blue-hover', true);
    // Here I'd like to pass that string as a class for the span child element. Can I have access to it from here?
  }
}

推荐答案

您可以像平常一样使用输入.初始化所有视图后,通常会在ngAfterViewInit中进行DOM操作,但由于会设置icon属性,并且您没有尝试访问的ViewChildren,因此它也可能会在ngOnInit中工作.

You can just use an input as you normally would. DOM manipulation would normally be done in the ngAfterViewInit when all views are initialized, but it will probably also work in the ngOnInit as the icon property will be set and you don't have any ViewChildren you try to access.

HTML:

<div sfw-navbar-square [sfwNavbarIcon]="'my-icon'">
  <span class="mdi mdi-magnify"></span>
</div>

这是指令本身(角度4):

Here's the directive itself (Angular 4):

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

@Directive({
  selector: '[sfw-navbar-square]'
})
export class NavbarSquareDirective {

  @Input('sfwNavbarIcon') icon:string;

  constructor(private el: ElementRef, private renderer: Renderer2) {
    this.renderer.addClass(this.el.nativeElement, 'navbar-square-item');
    this.renderer.addClass(this.el.nativeElement, 'pointer');
    this.renderer.addClass(this.el.nativeElement, 'met-blue-hover');
  }

  ngAfterViewInit() {
    let span = this.el.nativeElement.querySelector('span');
    this.renderer.addClass(span, this.icon);
  }
}

这篇关于我可以在Angular2的指令中访问子元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆