Javascript 动态选中在获取详细信息后动态附加到DOM的输入框

Javascript 动态选中在获取详细信息后动态附加到DOM的输入框,javascript,angular,dom,Javascript,Angular,Dom,我试图动态地检查一个输入框,但输入元素返回为未定义,因为当我尝试通过其ID获取元素并尝试检查该框时,它尚未添加到DOM中。我试图将操作包装在ngAfterViewInit()函数{}中,但这并没有奏效。关于如何仅在附加了所有输入选项后调用markPreviouslyVoted()函数,有什么建议吗 <input *ngFor="let choice of inputChoices" class="checkbox" type="checkbox" (click)="vote(choice.

我试图动态地检查一个输入框,但输入元素返回为未定义,因为当我尝试通过其ID获取元素并尝试检查该框时,它尚未添加到DOM中。我试图将操作包装在ngAfterViewInit()函数{}中,但这并没有奏效。关于如何仅在附加了所有输入选项后调用markPreviouslyVoted()函数,有什么建议吗

<input *ngFor="let choice of inputChoices" class="checkbox" type="checkbox" (click)="vote(choice.id)" id="{{choice.id}}" style="display: block; cursor: pointer;">

我是否可以在模板上使用此指令?可能类似于[ng init]=“Markpreviously投票()”

poll.component.ts

import { Component, OnInit } from '@angular/core';
import * as Chart from 'chart.js';
import { Observable } from 'rxjs';
import { FirebaseService } from '../services/firebase.service';
import { first } from 'rxjs/operators';
import { Input, Output, EventEmitter } from '@angular/core';
import { CardModule } from 'primeng/card';

@Component({
  selector: 'app-poll',
  templateUrl: './poll.component.html',
  styleUrls: ['./poll.component.scss']
})
export class PollComponent implements OnInit {
  chart:any;
  poll:any;
  votes:[] = [];
  labels:string[] = [];
  title:string = "";
  isDrawn:boolean = false;
  inputChoices:any = [];
  username:string = "";
  points:number;
  uid:string = "";
  votedChoice:string;

  @Input()
  pollKey: string;

  @Output()
  editEvent = new EventEmitter<string>();

  @Output()
  deleteEvent = new EventEmitter<string>();

  constructor(private firebaseService: FirebaseService) { }

  ngOnInit() {
    this.firebaseService.getPoll(this.pollKey).subscribe(pollDoc => {
      // ToDo: draw poll choices on create without breaking vote listener
      console.log("details?", pollDoc);
      // Return if subscription was triggered due to poll deletion
      if (!pollDoc.payload.exists) {
        return;
      }
      const pollData:any = pollDoc.payload.data();
      this.poll = {
        id: pollDoc.payload.id,
        helperText: pollData.helperText,
        pollType: pollData.pollType,
        scoringType: pollData.scoringType,
        user: pollData.user
      };

      if (this.poll.pollType == 1) {
        this.title = "A";
      }
      if (this.poll.pollType == 2) {
        this.title = "B";
      }
      if (this.poll.pollType == 3) {
        this.title = "C";
      }
      if (this.poll.pollType == 4) {
        this.title = "D";
      }

      // Populate username and user points
      this.firebaseService.getUser(pollData.user).subscribe((user:any) => {
        const userDetails = user.payload._document.proto;
        if (userDetails) {
        this.uid = user.payload.id;
        this.username = userDetails.fields.username.stringValue;
        this.points = userDetails.fields.points.integerValue;
        }
      });

      this.firebaseService.getChoices(this.pollKey).pipe(first()).subscribe(choices => {
        this.poll.choices = [];
        choices.forEach(choice => {
          const choiceData:any = choice.payload.doc.data();
          const choiceKey:any = choice.payload.doc.id;
          this.firebaseService.getVotes(choiceKey).pipe(first()).subscribe((votes: any) => {
            this.poll.choices.push({
              id: choiceKey,
              text: choiceData.text,
              votes: votes.length
            });
            // filter votes that equal userId and choiceId
            // if vote is found, check the box
            let hasVoted = votes.filter((vote) => {
              return (vote.payload.doc._document.proto.fields.choice.stringValue == choiceKey) &&
              (vote.payload.doc._document.proto.fields.user.stringValue == this.uid);
            });
            if (hasVoted.length > 0) {
              this.votedChoice = hasVoted[0].payload.doc._document.proto.fields.choice.stringValue;
            }
          });
          this.firebaseService.getVotes(choiceKey).subscribe((votes: any) => {
            if (this.isDrawn) {
              const selectedChoice = this.poll.choices.find((choice) => {
                return choice.id == choiceKey
              });
              selectedChoice.votes = votes.length;
              this.drawPoll();
            }
          });
        });
        setTimeout(() => {
          this.drawPoll();
        }, 1500)
      });
    });
  }

  drawPoll() {
    if (this.isDrawn) {
      this.chart.data.datasets[0].data = this.poll.choices.map(choice => choice.votes);
      this.chart.data.datasets[0].label = this.poll.choices.map(choice => choice.text);
      this.chart.update()
    }
    if (!this.isDrawn) {
      this.inputChoices = this.poll.choices;
      var canvas =  <HTMLCanvasElement> document.getElementById(this.pollKey);
      var ctx = canvas.getContext("2d");
      this.chart = new Chart(ctx, {
        type: 'horizontalBar',
        data: {
          labels: this.poll.choices.map(choice => choice.text),
          datasets: [{
            label: this.title,
            data: this.poll.choices.map(choice => choice.votes),
            fill: false,
            backgroundColor: [
              "rgba(255, 4, 40, 0.2)",
              "rgba(19, 32, 98, 0.2)",
              "rgba(255, 4, 40, 0.2)",
              "rgba(19, 32, 98, 0.2)",
              "rgba(255, 4, 40, 0.2)",
              "rgba(19, 32, 98, 0.2)"
            ],
            borderColor: [
              "rgb(255, 4, 40)",
              "rgb(19, 32, 98)",
              "rgb(255, 4, 40)",
              "rgb(19, 32, 98)",
              "rgb(255, 4, 40)",
              "rgb(19, 32, 98)",
            ],
            borderWidth: 1
          }]
        },
        options: {
          events: ["touchend", "click", "mouseout"],
          onClick: function(e) {
            console.log("clicked!", e);
          },
          tooltips: {
            enabled: true
          },
          title: {
            display: true,
            text: this.title,
            fontSize: 14,
            fontColor: '#666'
          },
          legend: {
            display: false
          },
          maintainAspectRatio: true,
          responsive: true,
          scales: {
            xAxes: [{
              ticks: {
                beginAtZero: true,
                precision: 0
              }
            }]
          }
        }
      });
      this.isDrawn = true;
    }
  }

  ngAfterViewInit() {
    this.markPreviouslyVoted();
  }

  markPreviouslyVoted() {
    let previouslyVoted:any = document.getElementById(this.votedChoice);
    if (previouslyVoted) {
      previouslyVoted.checked = true;
    }
  }

}
从'@angular/core'导入{Component,OnInit};
从“Chart.js”导入*作为图表;
从“rxjs”导入{Observable};
从“../services/firebase.service”导入{FirebaseService};
从“rxjs/operators”导入{first};
从“@angular/core”导入{Input,Output,EventEmitter};
从'priming/card'导入{cardmodel};
@组成部分({
选择器:“应用程序轮询”,
templateUrl:'./poll.component.html',
样式URL:['./poll.component.scss']
})
导出类PollComponent实现OnInit{
图表:任何;
投票:任何;
投票:[]=[];
标签:字符串[]=[];
标题:string=“”;
isDrawn:boolean=false;
inputChoices:any=[];
用户名:string=“”;
点数:数字;
uid:string=“”;
votedChoice:字符串;
@输入()
pollKey:字符串;
@输出()
editEvent=新的EventEmitter();
@输出()
deleteEvent=新的EventEmitter();
构造函数(私有firebaseService:firebaseService){}
恩戈尼尼特(){
this.firebaseService.getPoll(this.pollKey).subscribe(pollDoc=>{
//ToDo:在不中断投票侦听器的情况下在create上绘制投票选择
console.log(“详细信息”,pollDoc);
//如果由于轮询删除而触发订阅,则返回
如果(!pollDoc.payload.exists){
返回;
}
const pollData:any=pollDoc.payload.data();
本次投票={
id:pollDoc.payload.id,
helperText:pollData.helperText,
pollType:pollData.pollType,
scoringType:pollData.scoringType,
用户:pollData.user
};
if(this.poll.pollType==1){
this.title=“A”;
}
if(this.poll.pollType==2){
this.title=“B”;
}
if(this.poll.pollType==3){
this.title=“C”;
}
if(this.poll.pollType==4){
this.title=“D”;
}
//填充用户名和用户点
this.firebaseService.getUser(pollData.user).subscribe((用户:any)=>{
const userDetails=user.payload.\u document.proto;
如果(用户详细信息){
this.uid=user.payload.id;
this.username=userDetails.fields.username.stringValue;
this.points=userDetails.fields.points.integerValue;
}
});
this.firebaseService.getChoices(this.pollKey).pipe(first()).subscribe(choices=>{
this.poll.choices=[];
choices.forEach(choice=>{
const choiceData:any=choice.payload.doc.data();
const choiceKey:any=choice.payload.doc.id;
this.firebaseService.getVoices(choiceKey).pipe(first()).subscribe((投票:任意)=>{
这个.poll.choices.push({
id:choiceKey,
text:choiceData.text,
票数:票数
});
//筛选等于userId和choiceId的投票
//如果找到投票,请选中该框
让HasVote=投票。筛选((投票)=>{
return(vote.payload.doc.\u document.proto.fields.choice.stringValue==choiceKey)&&
(vote.payload.doc.\u document.proto.fields.user.stringValue==this.uid);
});
如果(hasvoluted.length>0){
this.votedChoice=hasvided[0]。payload.doc.\u document.proto.fields.choice.stringValue;
}
});
this.firebaseService.getVoces(choiceKey).subscribe((投票:任意)=>{
如果(此.isDrawn){
const selectedChoice=this.poll.choices.find((choice)=>{
return choice.id==choiceKey
});
selectedChoice.voces=voces.length;
this.drawPoll();
}
});
});
设置超时(()=>{
this.drawPoll();
}, 1500)
});
});
}
drawPoll(){
如果(此.isDrawn){
this.chart.data.datasets[0]。data=this.poll.choices.map(choice=>choice.voices);
this.chart.data.datasets[0]。label=this.poll.choices.map(choice=>choice.text);
this.chart.update()
}
如果(!this.isDrawn){
this.inputChoices=this.poll.choices;
var canvas=document.getElementById(this.pollKey);
var ctx=canvas.getContext(“2d”);
this.chart=新图表(ctx{
键入:“水平线”,
数据:{
标签:this.poll.choices.map(choice=>choice.text),
数据集:[{
标签:this.title,
数据:this.poll.choices.map(choice=>choice.voces),
填充:假,
背景颜色:[
“rgba(255,4,40,0.2)”,
“rgba(19,32,98,0.2)”,
“rgba(255,4,40,0.2)”,
“rgba(19,32,98,0.2)”,
“rgba(255,4,40,0.2)”,
rgba(19,32,98,0.2)
],
边框颜色:[
“rgb(255,4,40)”,
“rgb(19,32,98)”,
“rgb(255,4,40)”,
“rgb(19,32,98)”,
“rgb(255,4,40)”,
“rgb(19,32,98)”,
],
边框宽度:1
}]
},
选项:{
事件:[“touchend”、“click”、“mouseout”],
onClick:函数(e){
log(“单击!”,e);
},
工具提示:{
已启用:true
},
标题:{
显示:对,
文本:this.title,
尺寸:14,
fontColor:“#666”
<p-card>
  <p-header>
    <div style="float: left;">
      <i class="pi pi-pencil" style="font-size: 1.5em" (click)="edit()" style="cursor: pointer; margin-left: 8px;"></i>
      <i class="pi pi-trash" style="font-size: 1.5em" (click)="delete()" style="cursor: pointer; margin-left: 8px;"></i>
    </div>
    <div style="float: right;">
      <p style="margin-right: 8px; font-size: 10px;">Posted by {{username}} <i class="pi pi-star" style="font-size: 1.0em"></i>{{points}} points</p>
    </div>
  </p-header>
  <div class="chart-container" style="position: relative; width: 325px !important;">
    <canvas id="{{pollKey}}"></canvas>
    <div class="checkbox-container" style="position: absolute; top: 32px; left: 300px;">
      <input *ngFor="let choice of inputChoices" class="checkbox" type="checkbox" (click)="vote(choice.id)" id="{{choice.id}}" style="display: block; cursor: pointer;">
    </div>
  </div>
  <p-footer>
    <div style="text-align: left;
    background-color: rgba(19, 32, 98, 0.7);
    width: fit-content;
    padding: 5px;
    color: white;
    border-radius: 20px;
    font-size: 8px;
    font-weight: 600;">
      {{getScoringType()}}
    </div>
  </p-footer>
</p-card>