角度为2

时间:2017-09-29 08:29:57

标签: angular

我在组件html文件中有一个输入文本框。该文本框中的值将是我在该文本框中键入的文本,或者它必须来自使用md-dialog的自定义对话框。我能够获得当我点击对话框中的确认链接时,对话框中的值并显示在文本框中。

问题是在对话框中显示文本框中的值后,当我再次打开对话框并且只是单击取消它关闭对话框但是texbox中的值消失。我不想要.I想要在文本框中保留值,如果我只是再次打开对话框并在文本框中显示值后不做任何操作就关闭它。

如何实现?

我的主题模式组件代码:

cardDetails.component.ts

import { Component, OnInit,Inject ,Input,ElementRef } from '@angular/core';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import {SearchService} from '../sharedService/search.service';
import {ModalComponent} from './modal/modal.component';
import { Subject } from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
import { FormControl ,NgForm} from '@angular/forms';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import{BankdetailsService} from './modal/bankdetails.service';




@Component({
  selector: 'app-cardDetails',
  host: {
        '(document:click)': 'handleClick($event)',
    },
  templateUrl: './cardDetails.component.html',
  styleUrls: ['./cardDetails.component.css'],
  providers: [SearchService]
})
export class CardDetailsComponent implements OnInit {
   public query = '';
public filteredList = [];
    public elementRef;
    public banknames = ["ABHYUDAYA COOPERATIVE BANK LIMITED","ABU DHABI COMMERCIAL BANK","AHMEDABAD MERCANTILE COOPERATIVE BANK","AIRTEL PAYMENTS BANK LIMITED","AKOLA JANATA COMMERCIAL COOPERATIVE BANK","ALLAHABAD BANK","ALMORA URBAN COOPERATIVE BANK LIMITED","BANK","OTHER BANK","APNA SAHAKARI BANK LIMITED","AUSTRALIA AND NEW ZEALAND BANKING GROUP LIMITED","AXIS BANK","B N P PARIBAS","BANDHAN BANK LIMITED","BANK INTERNASIONAL INDONESIA","BANK OF AMERICA","BANK OF BAHARAIN AND KUWAIT BSC","BANK OF BARODA","BANK OF CEYLON","BANK OF INDIA","BANK OF MAHARASHTRA","BANK OF TOKYO MITSUBISHI LIMITED","BARCLAYS BANK","BASSEIN CATHOLIC COOPERATIVE BANK LIMITED","BHARAT COOPERATIVE BANK MUMBAI LIMITED","CANARA BANK","CAPITAL SMALL FINANCE BANK LIMITED","CATHOLIC SYRIAN BANK LIMITED","CENTRAL BANK OF INDIA","CHINATRUST COMMERCIAL BANK LIMITED","CITI BANK","CITIZEN CREDIT COOPERATIVE BANK LIMITED","CITY UNION BANK LIMITED","COMMONWEALTH BANK OF AUSTRALIA","CORPORATION BANK","CREDIT AGRICOLE CORPORATE AND INVESTMENT BANK CALYON BANK","CREDIT SUISEE AG","DCB BANK LIMITED","DENA BANK","DEOGIRI NAGARI SAHAKARI BANK LTD. AURANGABAD","DEPOSIT INSURANCE AND CREDIT GUARANTEE CORPORATION","DEUSTCHE BANK"]

submitted = false;
onSubmit() { this.submitted = true; }
bankdata: any[];
 ifsc : any;


queryField: FormControl = new FormControl();
searchTerm = new Subject<string>();
  constructor(private searchService: SearchService,public bankdetailservice : BankdetailsService, public dialog: MdDialog,myElement: ElementRef) { 

//this.searchService.search(this.searchTerm)
      //.subscribe(results => {
        //this.results = results.results;
      //});
 this.elementRef = myElement;
}



  ngOnInit() {

  this.queryField.valueChanges
  .debounceTime(200)
  .distinctUntilChanged()
  .switchMap((queryField) =>  this.searchService.search(queryField))
  .subscribe(data => { if (data.status === 400) { return; }
        else { 
        this.bankdata = data.data;
        console.log(typeof(this.bankdata));

                    }
        }
      );


}

filter() {
    if (this.query !== ""){
        this.filteredList = this.banknames.filter(function(el){
            return el.toLowerCase().indexOf(this.query.toLowerCase()) > -1;
        }.bind(this));

    }else{
        this.filteredList = [];
    }
}

select(item){
    this.query = item;
    this.filteredList = [];
}
handleClick(event){
   var clickedComponent = event.target;
   var inside = false;
   do {
       if (clickedComponent === this.elementRef.nativeElement) {
           inside = true;
       }
      clickedComponent = clickedComponent.parentNode;
   } while (clickedComponent);
    if(!inside){
        this.filteredList = [];
    }
}

//selectvalue(bnkname){


//}
openDialog(): void {
    let dialogRef = this.dialog.open(ModalComponent, {
      width: '250px',
      data: {  ifsc: this.ifsc }
    });

    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed');
      this.ifsc = result ;
    });
  }






}

carddetails component.html

<app-header></app-header>
<div class="container-fluid">
                <div class="row">
                    <div class="col-xs-12">
<h3 style="font-family: Lucida Console serif;color: rgba(0, 0, 0, 0.71);font-size: 17px;text-align: left;">Enter Payment Details</h3>
<p id ="plain">We require your bank details to transfer the <br>claim amount to you.<br>
<form (ngSubmit)="onSubmit()" #carddetailform = "ngForm" id="ngForm">


  <div class="form-group">
  <input type="text" class="form-control" id="name" name ="name"  placeholder="Full Name" required><br><br></div>
  <div class="form-group">
  <input type="text" class="form-control" id="ifsc" name ="ifsc"  [(ngModel)] = ifsctext  [value]="ifsc || '' " placeholder="IFSC Code" required></div>
  <p id ="message">Don't know your IFSC Code? That's okay, <a (click)="openDialog()">Find out here!</a><br><br>





<!--<input  type = "search" id="bank" (keyup)="searchTerm.next($event.target.value)" placeholder="BANK">
<ul *ngIf="results">
  <li *ngFor="let result of results | slice:0:9">

      {{ result.name }}

  </li>
</ul>-->

<!-- <section class="filter-wrapper"> -->
 <!--<div class="keyword-wrapper">-->
 <div class="form-group">
<input type="text" id="keyword" class="form-control" name ="bankname" [(ngModel)]=query (keyup)="filter()" placeholder="BANK"  [ngModelOptions]="{standalone: true}"/>

</div>

  <!--</div>-->


<div class="filter-select" *ngIf="filteredList.length > 0">
  <ul  *ngFor="let item of filteredList" class="filter-select-list"><li class="artist-name">

    <a (click)="select(item)">{{item}}</a>
  </li>

</ul>
</div>

<!-- <button type="submit"   [disabled]="!carddetailform.form.valid" form="ngForm" id ="button"class="form-control" routerLink="/endOfSurvey" >Send Bank Details</button> -->
<button type="submit" id ="button" class="form-control" routerLink="/endOfSurvey" >Send Bank Details</button>
  </form>
</div></div></div>

modal component.ts

import { Component, OnInit ,Inject,Input,Output,EventEmitter } from '@angular/core';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import { Select2OptionData } from 'ng2-select2';
import {BankdetailsService} from './bankdetails.service';

//import { ModalService } from './modal/modal.service';

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {
 banks = {};
 branch : any;
 city : any;
 ifsc : any;
 ifsctext;

 constructor(
    public dialogRef: MdDialogRef<ModalComponent>,
    @Inject(MD_DIALOG_DATA) public data: any, public bankdetailsservice : BankdetailsService) { }

  ngOnInit() {
this.bankdetailsservice.getBankInfo().subscribe(
      (data) => {
        this.banks = data.data;

        console.log(this.banks);
        },
          (error) => console.log("error : " + error),
          () => console.log('completed')
        );

       }

       firstDropDownChanged(val: any) {
    let obj = this.banks["BANK"];
    console.log(val, obj);

    if (!obj) return;

    if (obj == "YES BANK") {
      this.city = this.banks["CITY"];

      console.log(this.city);
    }

  }
   secondDropDownChanged(val: any) {
    let obj = this.banks["CITY"];
    console.log(val, obj);

    if (!obj) return;

    if (obj == "SURAT") {
      this.branch = this.banks["BRANCH"];

      console.log(this.branch);
    }
    if(this.branch)
    this.ifsc = this.banks["IFSC"];

    console.log(this.ifsc);
  }



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

modal component.html

 <div class="container-fluid">
                <div class="row">
                    <div class="col-xs-12">
                    <div md-dialog-content>
    <h3>Find your IFSC Code</h3>

<div class="form-group">

  <label for="sel1"></label>
  <select class="form-control selectpicker" id="sel1" (change)="firstDropDownChanged($event.target.selectedIndex -1)">
 <option data-hidden="true" value="">Bank Name</option>
 <option>
{{this.banks.BANK}}

 </option>


  </select>
  <label for="sel2"></label>
  <select class="form-control selectpicker" id="sel2" (change)="secondDropDownChanged($event.target.selectedIndex -1)">
    <option data-hidden="true" value="">City</option>
    <option>
{{this.city}}

 </option>

  </select>
  <label for="sel3"></label>
  <select class="form-control selectpicker" id="sel3">
    <option data-hidden="true" value="">Branch</option>
    <option>
        {{this.branch}}

    </option>
  </select>

</div>

<div md-dialog-actions>
<button md-button (click)="onNoClick()" tabindex="-1">Cancel</button>
  <button md-button  [md-dialog-close]="this.ifsc " tabindex="2">Confirm</button>

</div>
</div>
</div>
</div>
</div>

bankdetailservice.ts

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';


@Injectable()
export class BankdetailsService {
ifsctext ;
baseUrl: string = 'https://api.techm.co.in/api/getbank/YES%20BANK/ASSOCIATE%20COOP%20BANK%20UMARWADA';
  constructor(private http: Http) { 

    }

getBankInfo() {
    return this.http
        .get(this.baseUrl)
        .map(res => res.json());
  }



}

我的app module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
//import { ResponsiveState, ResponsiveConfig, ResponsiveConfigInterface } from 'responsive-directives-angular2'; 
//import {ResponsiveModule, ResponsiveConfig, ResponsiveConfigInterface} from 'ng2-responsive';
import { AppComponent } from './app.component';
import { MdFormFieldModule,MdInputModule} from '@angular/material';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MaterialModule} from '@angular/material';
import {MdDialogModule} from '@angular/material';
//import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import { ReactiveFormsModule } from '@angular/forms';
import { Select2Module } from 'ng2-select2';
//import { ModalModule } from 'ng2-modal-dialog/modal.module';


import { SecondComponent } from './second/second.component';
import { FirstserviceService } from './webServicesCall.service/firstservice.service';
import { Ng2DeviceDetectorModule, Ng2DeviceService } from 'ng2-device-detector';
import { CameraclickService } from './cameraclick.service';
import {BankdetailsService} from './cardDetails/modal/bankdetails.service';


import {RouterModule,Router,Routes} from '@angular/router';
import { CommonModule } from '@angular/common';
import { DefaultComponent } from './default/default.component';
import { HeaderComponent } from './header/header.component';
import {endOfSurveyComponent} from './endOfSurvey/endOfSurvey.component';
import {ProofOfRepairComponent} from './proofOfRepair/por.component';
import {SearchService} from './cardDetails/search.service';

//import { ClaimComponent } from './claim/claim.component';
//import { SurveyComponent } from './survey/survey.component';


import { CaptureclicksComponent } from './captureclicks/captureclicks.component';
import { CardDetailsComponent } from './cardDetails/cardDetails.component';
import { KeysPipe } from './second/keys.pipe';
import { ModalComponent } from './cardDetails/modal/modal.component';

const appRoutes: Routes = [
  { path: '', redirectTo: '/default', pathMatch: 'full' },
  { path: 'default', component: DefaultComponent },
  { path: 'second', component: SecondComponent},
  { path: 'captureclicks', component: CaptureclicksComponent},
  { path: 'proofOfRepair', component: ProofOfRepairComponent},
  {path: 'endOfSurvey', component: endOfSurveyComponent},
  {path: 'cardDetails', component: CardDetailsComponent}

];

@NgModule({
  declarations: [
    AppComponent,
    SecondComponent,
    DefaultComponent,
    HeaderComponent,
   endOfSurveyComponent,
   CaptureclicksComponent,
   ProofOfRepairComponent,
   CardDetailsComponent,
   KeysPipe,
   ModalComponent

  ],
  entryComponents: [ModalComponent],
  imports: [
    BrowserModule,
    MaterialModule,
    MdDialogModule,
    FormsModule,
    HttpModule,
    Select2Module,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    MdFormFieldModule,
    MdInputModule ,

    RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- debugging purposes only
    )
  ],
  providers:[FirstserviceService ,CameraclickService,BankdetailsService,SearchService,Ng2DeviceService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

我在模式html中有3个下拉列表。从三个下拉列表中选择值是银行详细信息后,它将给出一个ifsc代码,并且我在carddetails组件html中显示该代码,其中我有一个带有ifsc代码的文本框。 / p>

由于某些依赖性,我无法使用Stackblitz。请仔细研究并帮助我。谢谢

3 个答案:

答案 0 :(得分:0)

在调用类中,您是否检查对话框的返回值是否为NULL?

答案 1 :(得分:0)

只需将值保存在变量中,并在每次打开对话框时初始化此值。如果您有其他组件,则可以使用服务在组件之间进行通信。

https://angular.io/guide/component-interaction

编辑:

它有效

openDialog(): void {
    let dialogRef = this.dialog.open(ModalComponent, {
      width: '250px',
      data: {  ifsc: this.ifsc }
    });
    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed');
      if(result != '' && result != null ) {
      this.ifsc = result ;
      }
    });

如果它没有未定义或空字符串

,则检查和更改

答案 2 :(得分:0)

<强> =&GT;导入模块

import {MatDialogModule} from '@angular/material/dialog';

<强> =&GT;材料设计对话框

<ol>
  <li>
    <mat-form-field>
      <input matInput [(ngModel)]="name" placeholder="What's your name?">
    </mat-form-field>
  </li>
  <li>
    <button mat-raised-button (click)="openDialog()">Pick one</button>
  </li>
  <li *ngIf="animal">
    You chose: <i>{{animal}}</i>
  </li>
</ol>

=&gt; TS文件

import {Component, Inject} from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';

@Component({
  selector: 'dialog-overview-example',
  templateUrl: 'dialog-overview-example.html',
  styleUrls: ['dialog-overview-example.css'],
})
export class DialogOverviewExample {

  animal: string;
  name: string;

  constructor(public dialog: MatDialog) {}

  openDialog(): void {
    let dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
      width: '250px',
      data: { name: this.name, animal: this.animal }
    });

    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed');
      this.animal = result;
    });
  }

}

@Component({
  selector: 'dialog-overview-example-dialog',
  templateUrl: 'dialog-overview-example-dialog.html',
})
export class DialogOverviewExampleDialog {

  constructor(
    public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
    @Inject(MAT_DIALOG_DATA) public data: any) { }

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

}