【问题标题】:RESOLVED - Get attribute id from component in directive已解决 - 从指令中的组件获取属性 id
【发布时间】:2021-03-06 13:16:57
【问题描述】:

我正在尝试在自定义指令中获取组件(标头)的属性 ID。同时我正在使用布局来显示标题。为此,我使用this.renderer.appendChild(this.elementRef.nativeElement, p);,但问题是我需要将此段落添加到特定的div(<div #identifier class="mid"></div>)中。这是我的代码:

HTML 布局

<div class="grid">
  <header mId id="navbar"></header>
</div>

标题组件

<div class="header-container">
  <h1 id="logo">...</h1>
  .
  .
  .
  <div #identifier class="mid"></div>
</div>

指令

import { ContentChild, Directive, ElementRef, Renderer2, ViewChild } from '@angular/core';
import { myService } from 'src/app/myService/service';

@Directive({
  selector: '[mId]'
})
export class IdDirective {
  @ViewChild('identifier') mId: ElementRef;

  constructor(private renderer: Renderer2, private myService: Service, private elementRef: ElementRef) {
    this.method();
  }

  method() {
    this.service.getId().subscribe((response) => {
      const p = this.renderer.createElement('p');
      const text = this.renderer.createText('ID: ' + response.id);
      console.log(response.id);

      this.renderer.appendChild(p, text);
      this.renderer.appendChild(this.elementRef.nativeElement, p);
    });
  }

}

结果是 id 号被放置在底部布局的 &lt;header&gt; 标记内,例如:

<header mId id="navbar">
      <h1 id="logo">...</h1>
      .
      .
      .
      <div #identifier class="mid"></div>
      .
      .
      .
      <p>ID: 1</p>
</header>

我需要最终的结果是:

<header mId id="navbar">
      <h1 id="logo">...</h1>
      .
      .
      .
      <div #identifier class="mid">
           <p>ID: 1</p>
      </div>
</header>

谁能知道我该怎么做或者我做错了什么?

【问题讨论】:

标签: angular angular6 angular8 angular-directive directive


【解决方案1】:

要获取“标识符”,您应该使用 ContentChild,而不是 ViewChild,但您只能在 ViewInit 之后或在 setTimeout 中使用,以便让 Angular 有时间获取值

  @ContentChild('identifier') mId: ElementRef;

  constructor(private renderer: Renderer2, private elementRef: ElementRef) {
      setTimeout(()=>{
        this.method();
      })
  }

  method() {
    this.service.getId().subscribe((response) => {
      const response={id="currentID"} 
      const p = this.renderer.createElement('p');
      const text = this.renderer.createText('ID: ' + response.id);

      this.renderer.appendChild(p, text);
      this.renderer.appendChild(this.mId.nativeElement, p);

      this.renderer.setAttribute(this.mId.nativeElement,"id",response.id)
    })
  }

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 2018-03-15
    • 2020-09-05
    • 1970-01-01
    • 2022-01-10
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多