Добавить ng-select по нажатию кнопки Angular 8 - PullRequest
0 голосов
/ 22 марта 2020

У меня есть ng-select в моем DOM со значениями массива, я хочу добавить новый ng-select с такими же параметрами, нажав кнопку «Добавить», как я могу это сделать?

здесь мой компонент код, где я беру значение опций с сервера OnInit:


@Component({
  selector: 'app-recipes',
  templateUrl: './recipes.component.html',
  styleUrls: ['./recipes.component.scss']
})
export class RecipesComponent implements OnInit {

  @ViewChild('RicettaTestataForm2', {read: ElementRef}) private divMessages: ElementRef;
  public radioModel: string = '1';
  public Editor = InlineEditor;

  elencoRicette = [];
  elencoRicetteSelezionato = '';
  formRicettaTestata : FormGroup;

  constructor(private http: HttpClient, private formbuilder: FormBuilder, private render : Renderer2) { }

  ngOnInit(): void {
    this.formRicettaTestata = new FormGroup({
      titolo : new FormControl(null,Validators.required),
      difficolta : new FormControl(null, Validators.required),
      tempo_preparazione : new FormControl(null, Validators.required),
      immagine : new FormControl(null, Validators.required),

    });

    this.ritornaElencoIngredienti();

  }

  get ricettaTitolo(){
    return this.formRicettaTestata.get('titolo');
  }

  get ricettaTempoPreparazione(){
    return this.formRicettaTestata.get('tempo_preparazione');
  }

  ritornaElencoIngredienti(){
    this.http.get(environment.laravel_api+'/ricetta/ritorna-ingredienti').subscribe(
      data =>  this.AfterReturnIngredienti(data),
      error => console.log(error)
    );

  }

  AfterReturnIngredienti(data){

    this.elencoRicette = data['ingredienti'];
  }

  addIngrediente(){

  }

}

Вот раздел представления о ng-select, после нажатия на значок плюса я хочу иметь два ng-select:

....
<div class="col-md-6">
      <p class="h5 spazio-sopra">Ingredienti necessari</p>
      <form #RicettaTestataForm2="ngForm" [formGroup]="formRicettaTestata">
        <ng-select [items]="elencoRicette" bindLabel="nome" bindValue="id" [(ngModel)]="elencoRicetteSelezionato" [ngModelOptions]="{standalone:true}"></ng-select>
        <div>
          <mdb-icon fas icon="plus-circle" class="add-recepies-plus" (click)="addIngrediente()"></mdb-icon>
        </div>
      </form>
      <br>
    </div>
....

1 Ответ

0 голосов
/ 22 марта 2020

Я решил с помощью FormArray и для цикла в представлении.

В компоненте:

formIngredienti = new FormArray([
 new FormControl(null)
]);

У FormControl (null) есть хотя бы один элемент для цикла В моем view:

<ng-select class="select-ingredienti" *ngFor="let select of formIngredienti.controls;let i = index" [items]="elencoRicette" bindLabel="nome" bindValue="id" [(ngModel)]="elencoRicetteSelezionato[i]" [formControl]="formIngredienti.controls[i]"></ng-select>

С помощью formIngredienti.controls я циклически повторяю каждый formControl внутри FormArray

В действии кнопки я добавляю один элемент в FormArray с пустым FormControl:

this.formIngredienti.push(new FormControl(null));

Таким образом, я добавляю ng-select каждый раз, когда нажимаю кнопку «плюс»

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...