简体   繁体   English

如何将 getElementById 与 *ngIf 一起使用?

[英]How to use getElementById with *ngIf?

I'm trying to select a div which has a *ngIf on it:我正在尝试 select 一个具有 *ngIf 的 div:

<div id="explanation" *ngIf="isCorrect(option.optionValue)">

which returns null when I use getElementById.当我使用 getElementById 时返回 null。 If I remove ngIf it works fine, but I need to use the ngIf in my app.如果我删除 ngIf 它工作正常,但我需要在我的应用程序中使用 ngIf。 So how do I go about selecting the div?那么我如何 go 关于选择div?

EDIT: refactored code like this:编辑:重构代码如下:

<div [hidden]="!isCorrect(option.optionValue)">
  <div id="explanation">
    Option {{ question.answer }} is correct because {{ question.explanation }}.
  </div>
</div>


ngAfterViewInit() {
  let itemFrom = document.getElementById('explanation');
  let itemTo = document.getElementById('question');
}

radioChange(answer) {
  this.question.selectedOption = answer;
  this.answer.emit(answer);

  this.moveExplanation(this.itemFrom, this.itemTo);
}

moveExplanation(from, to) {
  to.replaceWith(from);
}

question and explanation are now both logged, replaceWith works, just need to remove the original explanation from underneath the correct answer and each question's explanation should move into the question box and similarly remove the explanation from underneath the correct answer.问题和解释现在都已记录,replaceWith 有效,只需从正确答案下方删除原始解释,每个问题的解释都应移入问题框,并同样从正确答案下方删除解释。

if you want to have access to your div with TypeScript, then you need to mark it with a Hashtag如果你想用 TypeScript 访问你的 div,那么你需要用 Hashtag 标记它

<div id="explanation" *ngIf="isCorrect(explanation)" #explanation>

and add the name into the parameter you use, to pass the value!并将名称添加到您使用的参数中,以传递值!

or with或与

<div [(ngModel)]="option"></div

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM