如何使用角度的另一个组件的布尔值在一个组件中隐藏和显示两个div

时间:2019-05-13 11:19:06

标签: angular event-handling observable decorator

先谢谢了。我正在为两个不同的参数设置一个Crud操作,例如Rule和Rule Parameter。在这里,两个组件都具有相似的CRUD操作组件(rule-add-model.component.ts及其html),为避免重复这些CRUD组件,我生成了布尔值isRowParam(rule-grid.component.ts及其html)。目的是如何将此布尔值传递给另一个组件,例如rule-add-model.component.ts及其包含两个div的html。

此处包含CRUD操作按钮,该按钮发出CRUD。

rule-grid.component.html

<app-grid-header (ActionClickedEvent)="onActionClicked($event)"></app-grid-header>
<div fxLayout="row" fxLayoutAlign="space-around center" >
<div style="background-color: teal;">
<kendo-grid [data]="records"
            [pageSize]="state.take"
            [skip]="state.skip"
            [sort]="state.sort"
            [sortable]="true"
            [pageable]="true"
            [scrollable]="'scrollable'"
            [groupable]="false"
            [group]="state.group"
            [filterable]="true"
            [filter]="state.filter"
            (dataStateChange)="dataStateChange($event)"
            [selectable]="true"
            (selectionChange)="gridUserSelectionChange(gridUser, $event)"
            [height]="500"
            [style.maxWidth.px]="1300"
            (cellClick)="onCellClick($event)"
            (dblclick)="onDblClick()"
            >
            <kendo-grid-column field=name title="Name"[width]="300"></kendo-grid-column>
            <kendo-grid-column field=type title="Rule Type" filter="numeric" [width]="250"></kendo-grid-column>
            <kendo-grid-column field=programName title="Program Name" ></kendo-grid-column>
           </kendo-grid>
        </div>

        <div style="background-color: teal" *ngIf="isRowParam">
            <kendo-grid [data]="record_RuleParms"
                        [pageSize]="state.take"
                        [skip]="state.skip"
                        [sort]="state.sort"
                        [sortable]="true"
                        [pageable]="true"
                        [scrollable]="'scrollable'"
                        [groupable]="false"
                        [group]="state.group"
                        [filterable]="true"
                        [filter]="state.filter"
                        (dataStateChange)="dataStateChange($event)"
                        [selectable]="true"
                        (selectionChange)="gridUserSelectionChange(gridUser, $event)"
                        [height]="500"
                        (dblclick)="onDblClick_Param()"
                        >
                        <kendo-grid-column field=name title="Name"[width]="300"></kendo-grid-column>
                        <kendo-grid-column field=defaultValue title="Default Value" filter="numeric" [width]="250"></kendo-grid-column>
                        <kendo-grid-column field=dataType title="Data Type" ></kendo-grid-column>
                       </kendo-grid>
                    </div>
                </div>

rule-grid.component.ts

 export class RuleGridComponent{


    private apiUrl: string = 'api/Rules';
    private selectedData: any;
    public records: GridDataResult;
    datas: any ;

    public clickedRowItem;
    public isRowParam=false;

    private apiUrlRuleParams: string='api/RuleParameters'
    public record_RuleParms:GridDataResult;

    private state: DataSourceRequestState = {
      skip: 0,
      take: 10
    };
    public grid: GridComponent;
    constructor(private ruleService: RulesService,private dataService: GridDataService, private dialog: MatDialog,private ngZone: NgZone,private excelService:ExcelService ) { }

   ngOnInit() {   
     this.dataService.fetch(this.state,this.apiUrl).subscribe(r => this.records = r);
  }

public dataStateChange(state: DataStateChangeEvent): void {
  this.state = state;
  this.dataService.fetch(state,this.apiUrl)
    .subscribe(r => this.records = r);

    this.fitColumns();
}

public ngAfterViewInit(): void {
  this.fitColumns();
}

private fitColumns(): void {
    this.ngZone.onStable.asObservable().pipe(take(1)).subscribe(() => {
    this.grid.autoFitColumns();
  });
}
 gridUserSelectionChange(gridUser, selection) {
  // let selectedData = gridUser.data.data[selection.index];
  const selectedData = selection.selectedRows[0].dataItem;
  console.log(selectedData);
  this.selectedData = selectedData;
}




//----------------------------------- Rule Type Grid --------------------------------------------- Boolean generates here  in onDblClick(e)----//
onCellClick(e) {
  this.clickedRowItem = e.dataItem;  
}

onDblClick(e) {
  console.log('Double click, data item: ', this.clickedRowItem);
  if(this.clickedRowItem!=null){
    this.isRowParam=true;

    this.dataService.fetch(this.state,this.apiUrlRuleParams+"/"+this.clickedRowItem.id)
    .subscribe((r :any)=> {
                    this.record_RuleParms = r.data;
                    console.log(this.record_RuleParms);
                  }
    )
  }
}


rule.add-model.ts

<div style="border-radius: .2em;border-color: teal" *ngIf="!isRowParam">
    <div fxLayout="row" fxLayoutAlign="space-between center" style="padding:1em;background-color: teal;color:white;">
        <h3>Add New Rule</h3>
    </div>
    <mat-divider class="mat-divider-custom" ></mat-divider>
    <form [formGroup]="ruleAddFormGroup" autocomplete="off" >
        <div fxLayout="column">
        <div fxLayout="row" fxLayoutAlign="space-between center">
            <div fxFlex="64" fxLayout="row" fxLayoutAlign="center center">
                <mat-form-field appearance="outline" class="w-100">
                    <mat-label>Name</mat-label>
                    <input autocomplete="off" maxlength="100" matInput placeholder="Enter Name" formControlName="name"
                        type="text">
                </mat-form-field>
            </div>
            <div fxFlex="64" fxLayout="row" fxLayoutAlign="center center">
               <!-- <mat-form-field appearance="outline" class="w-100" style="min-width:100%">
                    <mat-label>Rule Type</mat-label>
                    <input autocomplete="off" maxlength="100" matInput placeholder="Enter Rule Type" formControlName="type"
                        type="text">
                </mat-form-field> -->
                <mat-form-field appearance="outline" class="w-100">
                    <mat-label>Type</mat-label>
                    <mat-select disableOptionCentering="true" placeholder="Select the Rule Type" formControlName="type"
                        [(ngModel)]="ruletypes" >
                        <mat-option *ngFor="let t of actionType" [value]="t">
                            {{t.type}}
                        </mat-option>
                    </mat-select>
                </mat-form-field>
            </div>
            <div fxFlex="64" fxLayout="row" fxLayoutAlign="center center">
                <mat-form-field appearance="outline" class="w-100" style="min-width:100%">
                    <mat-label>Program Name</mat-label>
                    <input autocomplete="off" maxlength="100" matInput placeholder="Enter Program Name" formControlName="programName"
                        type="text">
                </mat-form-field>
            </div> 
         </div>       
        </div>

        <div fxLayout="row" fxLayoutAlign="end">
            <button mat-raised-button color="warn" (click)="onClose()">Cancel</button>
            <button mat-raised-button color="primary" (click)="onAdd()">Add</button>
        </div>
    </form>
    </div>



    <div style="border-radius: .2em;border-color: teal" *ngIf="isRowParam">
        <div fxLayout="row" fxLayoutAlign="space-between center" style="padding:1em;background-color: teal;color:white;">
            <h3>Add New Rule Parameter</h3>
        </div>
        <mat-divider class="mat-divider-custom" ></mat-divider>
        <form [formGroup]="ruleAddFormGroup" autocomplete="off" >
            <div fxLayout="column">
            <div fxLayout="row" fxLayoutAlign="space-between center">
                <div fxFlex="64" fxLayout="row" fxLayoutAlign="center center">
                    <mat-form-field appearance="outline" class="w-100">
                        <mat-label>Name</mat-label>
                        <input autocomplete="off" maxlength="100" matInput placeholder="Enter Name" formControlName="name"
                            type="text">
                    </mat-form-field>
                </div>
                <div fxFlex="64" fxLayout="row" fxLayoutAlign="center center">
                   <mat-form-field appearance="outline" class="w-100" style="min-width:100%">
                        <mat-label>Default Value</mat-label>
                        <input autocomplete="off" maxlength="100" matInput placeholder="Enter Default Value" formControlName="defaultValue"
                            type="text">
                    </mat-form-field>

                </div>
                <div fxFlex="64" fxLayout="row" fxLayoutAlign="center center">
                    <mat-form-field appearance="outline" class="w-100" style="min-width:100%">
                        <mat-label>Program Name</mat-label>
                        <input autocomplete="off" maxlength="100" matInput placeholder="Enter DataType" formControlName="sataType"
                            type="text">
                    </mat-form-field>
                </div> 
             </div>       
            </div>

            <div fxLayout="row" fxLayoutAlign="end">
                <button mat-raised-button color="warn" (click)="onClose()">Cancel</button>
                <button mat-raised-button color="primary" (click)="onAdd()">Add</button>
            </div>
        </form>
        </div>

rule-add-model.component.ts

import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { Component, EventEmitter } from '@angular/core';
import { MatDialogRef } from '@angular/material';
import { RulesService } from 'src/api/services';
import { SafeResourceUrl } from '@angular/platform-browser';
import { getTreeNoValidDataSourceError } from '@angular/cdk/tree';
import { filter, debounceTime } from 'rxjs/operators';
import { Observable } from 'rxjs/Rx';

@Component({
    selector: 'app-rule-add-model',
    templateUrl: './rule-add-model.component.html',
    //styleUrls: ['./rule-add-model.component.scss']
})
export class RuleAddComponent {
    ruleTypesService: RulesService;
    ruleAddFormGroup: FormGroup;
    onAddComplete: any = new EventEmitter<any>();
    onAddError: any = new EventEmitter<any>();
    onEdit = new EventEmitter();
    imageObj: SafeResourceUrl = '';
    ruletypes:string[];
    actionType:any;



    constructor(
        public dialogRef: MatDialogRef<RuleAddComponent>,
        private formBuilder: FormBuilder,
        private ruleService: RulesService) {
        this.dialogRef.disableClose = true;
        this.ruleAddFormGroup = this.formBuilder.group({
            name: ['', [Validators.required]],
            type:['1', [Validators.required]],
            programName:['', [Validators.required]],            
        });

        this.ruletypes =this.getRuleTypes();
      //  this.actionType=this.ruletypes;

    }
// Basic format to handle the Subscribe delay : NOTE: always add console.log() after the binding of datum.
    getRuleTypes():any{
           this.ruleService.GetRule().subscribe((res:any) => {
           this.actionType=res.data;
           this.ruletypes=res.data[0];
           console.log(res.data);          
        }
        )
    }

    onClose(): void {
        this.dialogRef.close();
    }

    onAdd() {
        if (this.ruleAddFormGroup.valid) {
            const rule = this.ruleAddFormGroup.value;
            console.log(JSON.stringify(rule));
            const data = {
                name: rule.name,
                type:rule.type["type"],
                programName:rule.programName               
            };
            debugger;
            this.ruleService.PostRule(data).subscribe(res => {
                debugger;
                if (res) {
                    this.onAddComplete.next(data);
                    this.dialogRef.close();
                }
            }, err => {
                this.onAddError.next(err.error);
                this.dialogRef.close();
            });

        } else {
            this.validateAllFormFields(this.ruleAddFormGroup);
        }
    }




    validateAllFormFields(formGroup: FormGroup) {
        Object.keys(formGroup.controls).forEach(field => {
            const control = formGroup.get(field);
            if (control instanceof FormControl) {
                control.markAsTouched({ onlySelf: true });
            } else if (control instanceof FormGroup) {
                this.validateAllFormFields(control);
            }
        });
    }

}

1 个答案:

答案 0 :(得分:0)

您可以使用service或使用@input @output,以便可以在两个组件之间传递数据。 默认情况下,您可以将isRowParam设置为false,然后将其他组件布尔值设置为isRowParam之后。因此div可以隐藏和显示。