【问题标题】:Angular 2 Input ID not getting bound to elementAngular 2输入ID未绑定到元素
【发布时间】:2022-02-21 06:25:55
【问题描述】:

我有一个 Angular 2 组件,它获取 elementId 作为输入,然后将其设置为 div 上的 id 属性。由于某种原因,没有设置 div 的 id。

@Component({
    selector: 'my-chart',
    template: `
        <div>
           Hello {{elementId}}
           <div [id]="elementId"></div>
        </div>
    `
})

export class MyChartComponent implements OnInit, OnChanges {
    @Input() elementId: string;

    ngOnInit() {
        this.createChart();
    }

    createChart() {
        console.log("ID: ", this.elementId);
        ...
    }
}

这是它在父组件中的样子:

<div *ngFor="let chart of charts">
    <my-chart [elementId]="chart.id"></my-chart>
</div>

--

当我检查 div 上的元素时,它显示没有在 HTML 元素上设置 id 属性。 Hello {{elementId}} 也只显示“Hello”。没有填写elementId。见下图。

但是console.log语句正确打印出id,说明输入绑定是正确的。

图片:Inspect Element shows id is missing

【问题讨论】:

    标签: javascript html angular


    【解决方案1】:

    document.getElementById(); 有一个等效的角度,你可以使用它。

    您可以像在 jQuery 中一样使用 angular 和 querySelector 中的元素引用 (ElementRef)。

      constructor(private elementRef: ElementRef) {
      }
    
      // this is inside any of the method
      // this is to select multiple 
      this.elementRef.nativeElement.querySelectorAll('.mandate');
    
      // this is to select single
      this.elementRef.nativeElement.querySelector('.mandate')
    

    所以与其使用文档,不如使用ElementRef

    【讨论】:

    • 我正在使用的库使用 document.getElementById,所以我在这件事上别无选择。这就是为什么我必须确保 div 的 id 属性设置正确。我已经编辑了我的问题以使其更清楚。
    • 添加了另一个答案
    【解决方案2】:

    在 Angular 生命周期中,AfterViewInit 是所有 html 和 js 绑定发生的地方。

    您应该在 AfterViewInit 方法中编写外部 dom monuplation。

    export class MyChartComponent implements OnInit, OnChanges, AfterViewInit {
        @Input() elementId: string;
    
        ngOnInit() {
    
        }
    
      ngAfterViewInit(): void {
            console.log("ID: ", this.elementId);
            Plotly.newPlot(this.elementId, ...);
      }
    }
    

    【讨论】:

    • 您好,感谢您的回答,但这也没有用。我认为问题与通话时间无关。问题是 div 的 id 没有设置。不再等待多久,id 仍然没有设置。 ngOnInit() 中的 console.log 显示 this.elementId 确实 存在并且正确绑定。
    • 嗯,这就是我得到的。让我们看看我们是否能得到更多答案
    • 嗨,Aniruddha,我已经更清楚地编辑了这个问题!谢谢
    • 大约一个小时后,这个解决方案突然开始起作用了!不知道为什么它最初不起作用。
    猜你喜欢
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 2017-03-19
    • 2017-08-07
    • 2016-10-01
    • 2015-05-11
    相关资源
    最近更新 更多