在获取详细信息之后动态地动态检查与DOM相连的输入框

时间:2019-04-06 02:46:01

标签: javascript angular dom

我试图动态检查输入框,但是输入元素返回未定义状态,因为当我尝试通过其ID获取元素并尝试检查该框时,尚未将其添加到DOM中。我试图将动作包装在ngAfterViewInit(){}函数内部,但这并不能解决问题。仅在附加所有输入选择后如何调用markPreviouslyVoted()函数的任何建议?

{
  "body": {
    "content": [
      {},
      {
        "paragraph": {
          "elements": [
            {
              "startIndex": 1,
              "endIndex": 5,
              "textRun": {
                "content": "abc\n",
                "textStyle": {}
              }
            }
          ]
        }
      },
      {
        "paragraph": {
          "elements": [
            {
              "startIndex": 5,
              "endIndex": 8,
              "textRun": {
                "content": "def",
                "textStyle": {
                  "link": {
                    "url": "https://sample/"
                  }
                }
              }
            },
            {
              "startIndex": 8,
              "endIndex": 9,
              "textRun": {
                "content": "\n",
                "textStyle": {}
              }
            }
          ]
        }
      }
    ]
  }
}

是否有可以在模板上使用的指令?也许像[ng-init] =“ markPreviouslyVoted()”这样的东西?

poll.component.ts

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

poll.component.html

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

}

1 个答案:

答案 0 :(得分:2)

考虑到仅选中复选框是您想要实现的目标...

您是否尝试过在输入中添加[checked] =“ == this.votedChoice”?