如何在jQuery / Angular 7中将一些值推入字符串之类的数组中

时间:2019-11-11 17:03:56

标签: jquery html angular

我有一些复选框,它们的值来自循环,我将这些值压入数组,但是在这里我的要求是,除了压入数组外,我还需要加入诸如“ parent1”,“ parent2”,“ parent3”之类的值并进行控制台。这是下面的代码

home.component.html

<li *ngFor="let child of nestedjson; let i = index"><input class="myCheckbox" type="checkbox" value="{{child.name}}" checked>{{child.name}}</li>
<div><button (click)="clear()" type="submit">clear</button></div>

home.component.ts

import {
  Component,
  OnInit
} from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';
import Speech from 'speak-tts';
import {
  RxSpeechRecognitionService,
  resultList,
} from '@kamiazya/ngx-speech-recognition';
import * as $ from 'jquery';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],

  providers: [RxSpeechRecognitionService]
})
export class HomeComponent implements OnInit {
  showit: any;
  nestedjson: any;
  constructor(private formBuilder: FormBuilder, public service: RxSpeechRecognitionService) {}

  ngOnInit() {
    this.nestedjson = [{
        name: "parent1",
        value: ["child11", "child12"]
      },
      {
        name: "parent2",
        value: ["child2"]
      },
      {
        name: "parent3",
        value: ["child3"]
      }
    ];
    this.showit = true;

  }

  clear() {
    var x = [];
    $(".myCheckbox:checked").each(function() {
      x.push($(this).val());
    });
    console.log(x);
  }

}

1 个答案:

答案 0 :(得分:0)

首先,尽可能不要将jQuery与Angular一起使用。您将弄乱Angular的更改检测的工作原理。

如果想在组件中检索UI状态,则可以对它进行第二个或更多的推论。您可以对它进行建模。您有一个字符串列表,并希望将其选中。而是将它们建模为:

class StringOption {
  public Text: string;
  public Value: string;
  public Checked: bool;
}

让模型确定是否已选中该复选框,这样您就不必查询DOM来获取状态。然后可以像这样构建字符串或所有选中选项的值的字符串:

let selected = options.filter(opt => opt.Checked).map(opt => opt.Text).join(', ');