【问题标题】:Weird behaviour querySelector奇怪的行为查询选择器
【发布时间】:2017-08-23 18:43:31
【问题描述】:

我有角度组件

在 component.ts 我有一行代码可以搜索 html 元素

var myArticle = document.querySelector('article');

这个返回空

在component.html中

<article id="bodyArticle" *ngIf="isClicked"></article>

但是当我在兄弟component.ts中使用文章时

var myArticle != null from component.ts

所有文件项目中的querySelector serach元素是如何工作的?

我还有其他问题。在同一个 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>

当我单击按钮时,发出的一次单击首先是值为真,我必须单击第二个按钮才能将其加载到文章内容中

来自component.ts的sn-p

  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);
    }
  }

当我单击文章标签 ngIf 中的按钮设置 true 值并且还加载数据时,如何做到这一点,而无需单击。

【问题讨论】:

  • 我们需要更多的描述。我相信您在组件安装到 DOM 之前调用了选择器。
  • @squgeim 我认为错误是 isclicked = false 并且元素尚未渲染并返回空值
  • 如果你的同级组件 在文章之后加载,那就是问题
  • 你什么时候调用你的方法,isClicked 一定是真的,是吗?
  • 打开你的控制台并运行document.querySelector('article');看它是否返回null

标签: javascript html angular


【解决方案1】:

尽量避免在 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,然后为文章设置。

<article #articleId id="bodyArticle" *ngIf="articleToggle"></article>

现在它会在第一次单击按钮后出现,因为这将是值从 false -> true 更改的唯一时间。

【讨论】:

  • 首先我将 isClicked 设置为 false。现在我更改为 true 但我希望这个元素在渲染视图后不可见。如何在单击按钮项后显示这篇文章。
  • 我也有一个问题,我必须先单击双按钮才能加载空文章,然后当我第二次单击时执行加载内容的方法 loadXML。也许你知道如何避免这种情况?我只会点击一次呈现带有内容的文章
  • 如果您定义并设置我展示的“articleToggled”布尔值而不是使用 isClicked 布尔值,则应该消除该行为。你可以扔掉它,或者只是改变它们的名字。 B
猜你喜欢
  • 1970-01-01
  • 2015-07-13
  • 1970-01-01
  • 1970-01-01
  • 2011-10-24
  • 1970-01-01
  • 2013-01-29
  • 2014-05-28
  • 1970-01-01
相关资源
最近更新 更多