Угловая модель управляемой формы нажатием на любую кнопку выполнит отправку - PullRequest
0 голосов
/ 10 июня 2019

Когда я нажимаю любую кнопку внутри формы, выполняются все функции, зарегистрированные внутри формы.

item.components.ts


    import { Component, OnInit } from '@angular/core';


    import { ItemsService } from '../../share/items.service';
    import { MatDialogRef } from '@angular/material';
    import { Item } from 'src/app/model/item';


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



      constructor(public service:ItemsService,
        public dialogRef: MatDialogRef<ItemComponent>) { }


      ngOnInit() {  }


      onSubmit(model: Item, isValid: boolean){
        console.log('!!! submit !!!');
      }

      addProperty(){
        console.log('!!! add prop !!!');
      }

      onClear(){
        console.log('!!! clear !!!');
      }


      onClose(){
        console.log('!!! close !!!');
      }


    }

item.ts


    export interface Item {
        id: BigInteger | null
        artNr: string;
        name: string;
        parentGroup: string;
        childGroup: string;
        properties: Array<{key: string, text: string}>;
    }

items.service.ts


    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders, HttpErrorResponse} from '@angular/common/http';
    import { Observable, from } from 'rxjs';

    import { FormGroup, FormControl, Validators, FormBuilder, FormGroupDirective, FormArray } from '@angular/forms' 
    import { Address } from '../model/address'; 
    import { Item } from '../model/item';

    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'Authorization': 'my-auth-token'
      })
    };

    interface ResponseItem{


      results:Item[];


    }


    @Injectable({
      providedIn: 'root'
    })


    export class ItemsService {


      constructor(private http:HttpClient, private formBuilder:FormBuilder) { }


      ngOnInit(){
        this.initializeItemFormGroup();
      }


      //** ITEM AREA */

      itemForm: FormGroup;


      initializeItemFormGroup(){
        this.itemForm = this.formBuilder.group({
          id: [null],
          artNr: ['', [Validators.required]],
          name: ['', [Validators.required]],
          parentGroup: ['', [Validators.required]],
          childGroup: [''],
          properties: this.formBuilder.array([this.addPropertyGroup()] )
        });
      }


      addPropertyGroup(){
        return this.formBuilder.group({
          key: [''],
          text: ['']
        })
      }


      removeProperty(index){
        this.property.removeAt(index);
      }


      addProperty() {
        this.property.push(this.addPropertyGroup());
      }


      get property():FormArray {
        return <FormArray>this.itemForm.get('properties');
      }
    }

item.component.html


    <form [formGroup]="service.itemForm" class="normal-form" (ngSubmit)="onSubmit(service.itemForm.value, service.itemForm.valid)">
      <mat-grid-list cols="2">
       <mat-grid-tile>
         <div class="controles-container">
           <input type="hidden" formControlName="id" >
           <mat-form-field>
             <input formControlName="artNr" matInput placeholder="EA0123" >
             <mat-error>Artikelnummer zwingend erforderlich</mat-error>
           </mat-form-field>
           <mat-form-field>
             <input formControlName="name" matInput placeholder="Artikelbezeichnung" >
             <mat-error>Bezeichnung ist erforderlich</mat-error>
           </mat-form-field>
           <mat-form-field>
             <input formControlName="parentGroup" matInput placeholder="Karosserie" >
           </mat-form-field>
           <mat-form-field>
             <input formControlName="childGroup" matInput placeholder="Schrauben" >
           </mat-form-field>
         </div>
       </mat-grid-tile>

       <mat-grid-tile>
         <button mat-icon-button (click)="addProperty()"><mat-icon>add</mat-icon></button>
         <div class="make-scrollable" formArrayName="properties">
           <div *ngFor="let property of service.itemForm.controls.properties?.value; let i=index;" class="panel panel-default">
             <ng-container [formGroupName]="i">
               <mat-form-field>
                 <input formControlName="key" matInput placeholder="Titel" >
               </mat-form-field>
               <mat-form-field>
                 <input formControlName="text" matInput placeholder="Beschreibender Text" >
               </mat-form-field>
             </ng-container>
           </div>
         </div>
       </mat-grid-tile>

       <mat-grid-tile  [colspan]="2">
           <div class="buttom-row">
               <button mat-raised-button color="primary" type="submit" [disabled]="service.itemForm.invalid">Speichern</button>
               <button mat-raised-button color="warn" (click)="onClear()">Bereinigen</button>
           </div>
        </mat-grid-tile>
      </mat-grid-list>
     </form>

Когда я нажимаю любую кнопку, консоль регистрируется (в настоящее время я пытался добавитьсвойство: (click) = "addProperty ()")

Вывод на консоль:

item.component.ts:32 !!! add prop !!!
item.component.ts:26 !!! submit !!!
item.component.ts:44 !!! close !!!

Но я ожидаю следующий вывод

Вывод на консоль:

item.component.ts:32 !!! add prop !!!

1 Ответ

0 голосов
/ 11 июня 2019

Спасибо Юлиусу Дзидзявичюсу.

Он сказал мне установить тип кнопки = "button"

Теперь все работает отлично !!!

См. Ниже

´´´HTML

 <form [formGroup]="service.itemForm" class="normal-form" (ngSubmit)="onSubmit(service.itemForm.value, service.itemForm.valid)">
      <mat-grid-list cols="2">
       <mat-grid-tile>
         <div class="controles-container">
           <input type="hidden" formControlName="id" >
           <mat-form-field>
             <input formControlName="artNr" matInput placeholder="EA0123" >
             <mat-error>Artikelnummer zwingend erforderlich</mat-error>
           </mat-form-field>
           <mat-form-field>
             <input formControlName="name" matInput placeholder="Artikelbezeichnung" >
             <mat-error>Bezeichnung ist erforderlich</mat-error>
           </mat-form-field>
           <mat-form-field>
             <input formControlName="parentGroup" matInput placeholder="Karosserie" >
           </mat-form-field>
           <mat-form-field>
             <input formControlName="childGroup" matInput placeholder="Schrauben" >
           </mat-form-field>
         </div>
       </mat-grid-tile>

       <mat-grid-tile>
         <button mat-icon-button type="button" (click)="addProperty()"><mat-icon>add</mat-icon></button>
         <div class="make-scrollable" formArrayName="properties">
           <div *ngFor="let property of service.itemForm.controls.properties?.value; let i=index;" class="panel panel-default">
             <ng-container [formGroupName]="i">
               <mat-form-field>
                 <input formControlName="key" matInput placeholder="Titel" >
               </mat-form-field>
               <mat-form-field>
                 <input formControlName="text" matInput placeholder="Beschreibender Text" >
               </mat-form-field>
             </ng-container>
           </div>
         </div>
       </mat-grid-tile>

       <mat-grid-tile  [colspan]="2">
           <div class="buttom-row">
               <button mat-raised-button color="primary" type="submit" [disabled]="service.itemForm.invalid">Speichern</button>
               <button mat-raised-button type="button" color="warn" (click)="onClear()">Bereinigen</button>
           </div>
        </mat-grid-tile>
      </mat-grid-list>
     </form>

´´´´

...