Как добавить новую строку в таблицу материалов - PullRequest
0 голосов
/ 25 декабря 2018

У меня есть выпадающий список и некоторые поля типов ввода, которые я выбираю в выпадающем списке, и я вписываю поле ввода, которое будет привязываться / показываться в таблице материалов?

Я сделал сHTML-код, но я пытался связать данные с помощью ngModel, но это невозможно для моей стороны

    <mat-tab label="Offer Library" class="no-overflow">

      <div *ngIf="isOfferCreationScreen ; else NewOffer">

        <!-- Code for button tab -->
        <div class="-toolbar">
          <p>
            <mat-toolbar>
              <h4>Offers Creation</h4>
              <div class="row align-right col-md-offset-9">
                <button (click)="createExpression()" disabled mat-raised-button>
                  inActive
                </button>
                <button color="primary" disabled mat-raised-button>
                  Delete
                </button>
                <button mat-raised-button (click)="createNewOffer()" type="button">
                  Create New
                </button>
              </div>
            </mat-toolbar>
          </p>
        </div>

        <mat-table [dataSource]="offersColumnRowData" class="mat-table no-overflow">

          <ng-container matColumnDef="SELECT">
            <mat-header-cell *matHeaderCellDef> SELECT </mat-header-cell>
            <mat-cell *matCellDef="let element"> </mat-cell>
          </ng-container>

          <ng-container matColumnDef="NAME">
            <mat-header-cell *matHeaderCellDef> NAME </mat-header-cell>
            <mat-cell *matCellDef="let element"> </mat-cell>
          </ng-container>

          <ng-container matColumnDef="CODE">
            <mat-header-cell *matHeaderCellDef> CODE </mat-header-cell>
            <mat-cell *matCellDef="let element"> </mat-cell>
          </ng-container>

          <ng-container matColumnDef="DESCRIPTION">
            <mat-header-cell *matHeaderCellDef> DESCRIPTION </mat-header-cell>
            <mat-cell *matCellDef="let element"> </mat-cell>
          </ng-container>

            <ng-container matColumnDef="LEVEL 1">
            <mat-header-cell *matHeaderCellDef> LEVEL 1</mat-header-cell>
            <mat-cell *matCellDef="let element"> </mat-cell>
          </ng-container>

           <ng-container matColumnDef="LEVEL 2">
            <mat-header-cell *matHeaderCellDef> LEVEL 2</mat-header-cell>
            <mat-cell *matCellDef="let element"> </mat-cell>
          </ng-container>

            <ng-container matColumnDef="LEVEL 3">
            <mat-header-cell *matHeaderCellDef> LEVEL 2</mat-header-cell>
            <mat-cell *matCellDef="let element"> </mat-cell>
          </ng-container>


             <ng-container matColumnDef="LEVEL 4">
            <mat-header-cell *matHeaderCellDef> LEVEL 2</mat-header-cell>
            <mat-cell *matCellDef="let element"> </mat-cell>
          </ng-container>

              <ng-container matColumnDef="LEVEL 5">
            <mat-header-cell *matHeaderCellDef> LEVEL 2</mat-header-cell>
            <mat-cell *matCellDef="let element"> </mat-cell>
          </ng-container>

          <ng-container matColumnDef="CREATEDATE">
            <mat-header-cell *matHeaderCellDef> CREATEDATE </mat-header-cell>
            <mat-cell *matCellDef="let element"> </mat-cell>
          </ng-container>

          <ng-container matColumnDef="ISACTIVE">
            <mat-header-cell *matHeaderCellDef> ISACTIVE </mat-header-cell>
            <mat-cell *matCellDef="let element"> </mat-cell>
          </ng-container>

          <ng-container matColumnDef="UNAME">
            <mat-header-cell *matHeaderCellDef> UNAME </mat-header-cell>
            <mat-cell *matCellDef="let element"> </mat-cell>
          </ng-container>

          <ng-container matColumnDef="Active">
            <mat-header-cell *matHeaderCellDef> Active </mat-header-cell>
            <mat-cell *matCellDef="let element"> </mat-cell>
          </ng-container>

          <mat-header-row *matHeaderRowDef="offersColumns"></mat-header-row>
          <mat-row *matRowDef="let row; columns: offersColumns;"></mat-row>
        </mat-table>


      </div>
      <ng-template #NewOffer>


        <div class="window-pad-height no-overflow">
          <h4>New Offers</h4>

          <div class="row no-overflow">
            <div class="col-md-1 window-pad-height no-overflow">

              <!-- Write Offer Name here -->
              <mat-label> Name: </mat-label>
            </div>
            <div class="col-md-2 no-overflow">
              <mat-form-field>
                <input matInput placeholder="Name" [(ngModel)]="offerName" value="" [formControl]="control"
                  required>
                <mat-error *ngIf="control.invalid">{{getErrorMsg()}}</mat-error>
              </mat-form-field>
            </div>
          </div>
          <!-- Write offer Code Here -->
          <div class="row no-overflow">
            <div class="col-md-1 window-pad-height no-overflow">
              <mat-label> Code: </mat-label>
            </div>
            <div class="col-md-2 no-overflow">
              <mat-form-field>
                <input matInput placeholder="Code" value="">
              </mat-form-field>
            </div>
          </div>

          <!-- Write Offer Decription here -->
          <div class="row no-overflow">
            <div class="col-md-1 window-pad-height no-overflow">
              <mat-label> Description: </mat-label>
            </div>
            <div class="col-md-2 no-overflow">
              <mat-form-field appearance="outline" class="descriptionInput">
                <textarea matInput></textarea>
              </mat-form-field>
            </div>
          </div>

          <!-- level One  Offer for Drop Down -->
          <div class="row no-overflow">
            <div class="col-md-1 window-pad-height no-overflow">
              <mat-label> Level 1: </mat-label>
            </div>
            <div class="col-md-2 no-overflow">
              <mat-form-field class="no-overflow">
                <mat-select placeholder="select" [(ngModel)]="selectedOfferOne">
                  <mat-option *ngFor="let levelone of levelOneOffer" [value]="levelone">
                    {{levelone.viewValue}}

                  </mat-option>
                </mat-select>
              </mat-form-field>
            </div>
          </div>

          <!-- level Two  Offer for Drop Down -->
          <div class="row no-overflow">
            <div class="col-md-1  no-overflow">
              <mat-label> Level 2: </mat-label>
            </div>
            <div class="col-md-2 no-overflow">
              <mat-form-field class="no-overflow">
                <mat-select placeholder="select" [(ngModel)]="selectedOfferTwo">
                  <mat-option *ngFor="let leveltwo of levelTwoOffer" [value]="leveltwo">
                    {{leveltwo.viewValue}}
                  </mat-option>
                </mat-select>
              </mat-form-field>
            </div>
          </div>

          <!-- level Three Offer for Drop Down -->
          <div class="row no-overflow">
            <div class="col-md-1 no-overflow">
              <mat-label> Level 3: </mat-label>
            </div>
            <div class="col-md-2 no-overflow">
              <mat-form-field class="no-overflow">
                <mat-select placeholder="select" [(ngModel)]="selectedOfferThree">
                  <mat-option *ngFor="let levelthree of levelThreeOffer" [value]="levelthree">
                    {{levelthree.viewValue}}
                  </mat-option>
                </mat-select>
              </mat-form-field>
            </div>
          </div>


          <!-- level Four Offer for Drop Down -->
          <div class="row no-overflow">
            <div class="col-md-1 no-overflow">
              <mat-label> Level 4: </mat-label>
            </div>
            <div class="col-md-2 no-overflow">
              <mat-form-field class="no-overflow">
                <mat-select placeholder="select" [(ngModel)]="selectedOfferFour">
                  <mat-option *ngFor="let levelfour of levelFourOffer" [value]="levelfour">
                    {{levelfour.viewValue}}
                  </mat-option>
                </mat-select>
              </mat-form-field>
            </div>
          </div>

          <!-- level Five Offer for Drop Down -->
          <div class="row no-overflow">
            <div class="col-md-1 no-overflow">
              <mat-label> Level 5: </mat-label>
            </div>
            <div class="col-md-2 no-overflow">
              <mat-form-field class="no-overflow">
                <mat-select placeholder="select" [(ngModel)]="selectedOfferFive">
                  <mat-option *ngFor="let levelfive of levelFiveOffer" [value]="levelfive">
                    {{levelfive.viewValue}}
                  </mat-option>
                </mat-select>
              </mat-form-field>
            </div>
          </div>

          <!-- Select check box isActive -->
          <div class="row no-overflow window-pad-height">
            <div class="col-md-1 no-overflow ">
              <mat-checkbox>IsActive</mat-checkbox>
            </div>
          </div>
          <div class="window-pad-height">
            <div class="row col-md-3 no-overflow">

              <!-- back button for Offer Creation -->

              <button mat-flat-button color="primary" (click)="backtoOfferCreation()">Back</button>
            </div>

            <!-- Save Button for New Created Offer -->
            <div class="col-md-1 no-overflow">
              <button mat-flat-button color="primary" [disabled]=" offerName===''|| selectedOfferOne==='' || selectedOfferTwo==='' || selectedOfferThree===''
              ||selectedOfferFour===''|| selectedOfferFive==='' ">Save</button>
            </div>

            <div class="col-md-1 no-overflow">

              <!-- Move to Campaign Library Tab -->

              <button mat-flat-button color="primary" [disabled]=" offerName===''|| selectedOfferOne==='' || selectedOfferTwo==='' || selectedOfferThree===''
              ||selectedOfferFour===''|| selectedOfferFive===''">Next</button>
            </div>

          </div>

        </div>

      </ng-template>

  </mat-tab>

Код файла TS:

 export class OffersComponent implements OnInit {

 // created offer list table   

    offersColumns = ['SELECT', 'NAME', 'CODE', 'DESCRIPTION', 'CREATEDATE', 
 'ISACTIVE', 'UNAME', 'LEVEL 1','LEVEL 2','LEVEL 3','LEVEL 4','LEVEL 5',  'Active'];

  offersColumnRowData = [];
// condition for create new template
   isOfferCreationScreen = true;
// drop down  for selected offer
 selectedOfferOne = '';
 selectedOfferTwo = '';
 selectedOfferThree = '';
 selectedOfferFour = '';
 selectedOfferFive = '';
 offerName = '';
 // form validation for user input for Offer Library
 control = new FormControl('', [Validators.required, 
Validators.minLength(4)]);

 // level One to level Five Static Data Create new Offer template
 levelOneOffer = [] = [
{ value: 'col-1', viewValue: 'info1' },
{ value: 'col-2', viewValue: 'info2' },
{ value: 'col-3', viewValue: 'info3' },
{ value: 'col-4', viewValue: 'info4' }
]
     levelTwoOffer = [] = [
{ value: 'col-1', viewValue: 'Data1' },
{ value: 'col-2', viewValue: 'Data2' },
{ value: 'col-3', viewValue: 'Data3' }
 ]
  levelThreeOffer = [] = [
 { value: 'col-1', viewValue: 'info1' },
{ value: 'col-2', viewValue: 'info2' },
 { value: 'col-3', viewValue: 'info3' },
  { value: 'col-4', viewValue: 'info4' },
{ value: 'col-1', viewValue: 'info5' },
{ value: 'col-1', viewValue: 'info6' }
 ]

   levelFourOffer = [] = [
{ value: 'col-1', viewValue: 'info1' },
{ value: 'col-2', viewValue: 'info2' },
{ value: 'col-3', viewValue: 'info3' },
{ value: 'col-4', viewValue: 'info4' },
{ value: 'col-1', viewValue: 'info5' },
{ value: 'col-1', viewValue: 'info6' }
   ]

    levelFiveOffer = [] = [
    { value: 'col-1', viewValue: 'info1' },
    { value: 'col-2', viewValue: 'info2' },
    { value: 'col-3', viewValue: 'info3' },
    { value: 'col-4', viewValue: 'info4' },
    { value: 'col-1', viewValue: 'info5' },
    { value: 'col-1', viewValue: 'info6' }
   ]



    constructor(private snakbar: SnakBarComponent, public dialog: 
 MatDialog, public globalAppSateService: GlobalAppSateService,
     private dataService: DataService) {
this.getErrorMsg();

}
 // method for form validation Offer Library
  getErrorMsg() {
return this.control.hasError('required') ? 'You must enter a Name here' :
  this.control.hasError('minlength') ? 'You must enter atleast four 
characters' :
    '';
  }
 // button click even for new new button Offer Library
  createNewOffer() {
   this.isOfferCreationScreen = false;
 };
 backtoOfferCreation() {
   this.isOfferCreationScreen = true;
 };

 ngOnInit() {


}

}

независимо от того, какой тип ввода я вписываю и какой выбираюв раскрывающемся списке, который должен быть добавлен в матовую таблицу*

1 Ответ

0 голосов
/ 26 декабря 2018

Если вы используете двустороннюю привязку данных, я бы предложил создать интерфейс и связать свойство интерфейса с [(ngModel)]

In Component:

export interface Employee {
  name: string
  id:string
}

В HTML Bind Likethis:

<mat-form-field class="example-full-width">
    <input matInput placeholder="Name" [(ngModel)]="employee.name"> // here 
  </mat-form-field>

  <mat-form-field>
  <mat-select [(ngModel)]="employee.id">
    <mat-option>None</mat-option>
    <mat-option value="1">Option 1</mat-option>
    <mat-option value="3">Option 2</mat-option>
    <mat-option value="6">Option 3</mat-option>
  </mat-select>
</mat-form-field>

Так что ваша функция addNew() содержит меньше кода, так как вам просто нужно добавить объект сотрудника в список и обновить источник данных:

Код Component.TS:

import { MatTableDataSource } from '@angular/material'; // import this

export interface Employee {
  name: string
  id:string
}

employee : Employee = {
   id :"",
   name :""
}; /// This could refactor

displayedColumns: string[] = ['name', 'id'];
dataSource = new MatTableDataSource(ELEMENT_DATA);

addNew(){
   ELEMENT_DATA.push(this.employee)
   this.dataSource = new MatTableDataSource(ELEMENT_DATA);
   this.employee = {
     id :"",
     name :""
   };   /// This could refactor
}

Так что в случае любого нового поля просто добавьте в Интерфейс и в HTML к [(ngModel)].

WORKING DEMO

...