我有 Angular 组件
在 component.ts 中,我有一行代码用于搜索 html 元素
var myArticle = document.querySelector('article');
此返回 null
在组件.html
<article id="bodyArticle" *ngIf="isClicked"></article>
但是当我在同级 component.ts 中使用文章时
var myArticle != null from component.ts
querySelector 搜索元素在所有文件项目中如何工作?
我还有其他问题。在同一个 componen.html 中我有按钮
<div class="btnGrp">
<button (click)="loadXML($event)">Load</button>
<input type="file" name="img" multiple (change)="onChange($event)">
</div>
<article id="bodyArticle" *ngIf="isClicked"></article>
当我单击按钮时,发出的一次单击首先值为 true,我必须单击第二个按钮才能将其加载到文章内容
来自 component.ts 的片段
loadXML(event?: Event) {
var myArticle = document.querySelector('article');
console.log(myArticle);
if(this.imageService.getBodyRes() == ''){
myArticle.textContent = 'Error can't load data';
this.isClicked = true;
this.xmlLoadedEvent.emit(this.isClicked);
} else {
myArticle.textContent = this.imageService.getBodyRes();
console.log(myArticle.textContent);
this.isClicked = true;
this.xmlLoadedEvent.emit(this.isClicked);
}
}
当我单击文章标签 ng 中的按钮时如何执行此操作如果设置 true 值并且在不单击的情况下加载数据。
最佳答案
尽量避免在 Angular 中使用文档对象及其方法。如果你尝试这样做,你的生活将会变得非常困难。
<article #articleId id="bodyArticle" *ngIf="isClicked"></article>
您可以在文章标签上放置一个模板变量名称,然后使用 Angular 的“ViewChild”类对其进行查询,如下所示 -
import { Component, ViewChild, ElementRef, ...others?....} from '@angular/core'
export class MyComponent {
articleToggle: boolean = false; // add a toggle in your component for turning the article on
@ViewChild('articleId') article: ElementRef;
ngAfterViewInit() {
this.article.nativeElement.<<access DOM attributes here>>
}
}
这将使您能够访问 DOM 节点,就像您期望文档查询完成的那样,但即便如此,可能仍然有更好的方法来完成您正在做的事情,特别是因为您提到您正在尝试使用兄弟组件中的文章。如果是这种情况,您可能希望将其设为自己的组件,从而完全避免查询,但同样,信息如此之少是不可能知道的。
此外,通常建议避免在 typescript 中完全与 null 进行比较。请改用“未定义”。
<button (click)="loadXML($event); articleToggle = true">Load</button>
在点击时将变量设置为 true,然后在文章中将变量设置为 true。
<article #articleId id="bodyArticle" *ngIf="articleToggle"></article>
现在它将在第一次单击按钮后出现,因为这是值从 false -> true 更改的唯一一次。
关于javascript - 奇怪的行为querySelector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45836850/