Angular與模態框的通訊

来源:http://www.cnblogs.com/nangxi/archive/2017/11/21/7874398.html
-Advertisement-
Play Games

Angular做項目的時候,難免會用到彈框(即模態框),如果模態框裡面有一張表格,表格裡面的數據需要從父組件(這裡暫且先說成父組件吧!)裡面獲取,模態框的表格裡面的數據經過修改,又傳回給父組件,這種通訊方式該怎麼實現?我們先來看一下最基本的自定義彈框代碼,看看有沒有什麼突破口。 一、基本的自定義彈框 ...


Angular做項目的時候,難免會用到彈框(即模態框),如果模態框裡面有一張表格,表格裡面的數據需要從父組件(這裡暫且先說成父組件吧!)裡面獲取,模態框的表格裡面的數據經過修改,又傳回給父組件,這種通訊方式該怎麼實現?我們先來看一下最基本的自定義彈框代碼,看看有沒有什麼突破口。

一、基本的自定義彈框代碼

1.demo目錄

----------app.component.ts

----------app.component.html

----------app.module.ts

----------confirm(文件夾)

------------confirm.component.ts

------------confirm.component.html

2.項目代碼

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { CommonModule } from "@angular/common";
import { BootstrapModalModule } from 'ngx-bootstrap-modal';
import { AppComponent } from './app.component';
import { ConfirmComponent } from './confirm/confirm.component';

@NgModule({
  declarations: [
    AppComponent,
    ConfirmComponent
  ],
  imports: [
    CommonModule,
    BrowserModule,
    BootstrapModalModule
  ],
  providers: [],
  bootstrap: [AppComponent],
  entryComponents: [
    ConfirmComponent
    ]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { ConfirmComponent } from './confirm/confirm.component';
import { DialogService } from "ngx-bootstrap-modal";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
   constructor(private dialogService:DialogService) {}
    showConfirm() {
        this.dialogService.addDialog(ConfirmComponent, {
            title:'Confirm title', 
            message:'Confirm message'})
            .subscribe((isConfirmed)=>{
                if(isConfirmed) {}
                else {}
            });
    }
}

app.component.html

<button type="button" class="btn btn-primary" (click)="showConfirm()">彈框</button>

confirm.component.ts

import { Component } from '@angular/core';
import { DialogComponent, DialogService } from "ngx-bootstrap-modal";
export interface ConfirmModel {
  title:string;
  message:string;
}

@Component({  
    selector: 'confirm',
    templateUrl: './confirm.component.html',
    styleUrls: ['./confirm.component.css']
})
export class ConfirmComponent extends DialogComponent<ConfirmModel, boolean> implements ConfirmModel {
  title: string;
  message: string;

  // 構造函數需要一個DialogService參數
  constructor(dialogService: DialogService) {
    super(dialogService);
  }
  
  confirm() {
    // result是一個boolean類型,這一點取決於{DialogComponent<ConfirmModel, boolean>}
    this.result = true;
    // close() 方法是由 `DialogComponent` 定義的,用於關閉模態框。在HTML模板中也有可以調用。
    this.close(); 
  }
}

confirm.component.html

<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" (click)="close()" >×</button>
      <h4 class="modal-title">{{title}}</h4>
    </div>
    <div class="modal-body">
      <p>{{message}}</p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-primary" (click)="confirm()">OK</button>
      <button type="button" class="btn btn-default" (click)="close()" >Cancel</button>
    </div>
  </div>
</div>

3.分析

我們來看一下app.component.ts和confirm.component.ts裡面的title和message,感覺好像有點貓膩。我們看一下效果圖就知道了。

我們會發現,這個Confirm title和Confirm message不就是通過app.component.ts裡面的title和message傳進去的嘛?那這就好辦了,至少可以證明,父組件的數據可以傳到彈框裡面。那麼我們再修改一下這個項目,讓它實現父組件表格裡面的數據傳遞到彈框裡面並且把它渲染出來。

二、父組件數據傳遞到彈框

1.demo目錄(項目目錄不變)

2.項目代碼

app.component.ts

import { Component } from '@angular/core';
import { ConfirmComponent } from './confirm/confirm.component';
import { DialogService } from "ngx-bootstrap-modal";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  datas=[//父組件裡面的數據
    {
      name:"Mr.Chen",
      id:1001
    },
    {
      name:"Miss.Lee",
      id:1003
    },
    {
      name:"Mr.Fang",
      id:1006
    },
    {
      name:"Miss.Lin",
      id:1009
    }
  ]
  constructor(private dialogService:DialogService) {}
  showConfirm() {
    this.dialogService.addDialog(ConfirmComponent, {
      title:'Confirm title', 
      message: this.datas//傳遞給彈框
    })
    .subscribe((isConfirmed)=>{
      if(isConfirmed) {}
      else {}
      });
    }
} 

app.component.html(在父組件渲染)

<button type="button" class="btn btn-primary" (click)="showConfirm()">彈框</button>
<table class="table">
  <tr>
    <th>編號</th>
    <th>姓名</th>
    <th>學號</th>
  </tr>
  <tr *ngFor="let data of datas;let i=index">
    <td>{{i+1}}</td>
    <td>{{data.name}}</td>
    <td>{{data.id}}</td>
  </tr>
</table>

confirm.component.ts

import { Component,OnInit } from '@angular/core';
import { DialogComponent, DialogService } from "ngx-bootstrap-modal";
export interface ConfirmModel {
  title:string;
  message:any; //註意這裡的介面類型要更改
}

@Component({  
    selector: 'confirm',
    templateUrl: './confirm.component.html',
    styleUrls: ['./confirm.component.css']
})
export class ConfirmComponent extends DialogComponent<ConfirmModel, boolean> implements ConfirmModel {
  title: string;
  message: any;//這裡的類型也要更改
  ArrayData:any;
  ngOnInit(){
    this.ArrayData=this.message;//將父組件傳遞過來的值賦值給新的變數
  }
  // 構造函數需要一個DialogService參數
  constructor(dialogService: DialogService) {
    super(dialogService);
  }
  
  confirm() {
    // result是一個boolean類型,這一點取決於{DialogComponent<ConfirmModel, boolean>}
    this.result = true;
    // close() 方法是由 `DialogComponent` 定義的,用於關閉模態框。在HTML模板中也有可以調用。
    this.close(); 
  }
}

confirm.component.html(在彈框中渲染)

<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" (click)="close()" >×</button>
      <h4 class="modal-title">{{title}}</h4>
    </div>
    <div class="modal-body">
      <table class="table">
        <tr>
          <th>編號</th>
          <th>姓名</th>
          <th>學號</th>
        </tr>
        <tr *ngFor="let Data of ArrayData;let i=index">
          <td>{{i+1}}</td>
          <td>{{Data.name}}</td>
          <td>{{Data.id}}</td>
        </tr>
      </table>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-primary" (click)="confirm()">OK</button>
      <button type="button" class="btn btn-default" (click)="close()" >Cancel</button>
    </div>
  </div>
</div>

至此我們實現的只是數據從父組件到彈框的單向傳遞,我們來看一下效果。

三、彈框數據返傳給父組件

那麼反過來呢?彈框的數據要怎麼傳遞給它的父組件,我們再來深究一下彈框裡面的代碼。

在app.component.ts裡面,有一個判斷語句if(isConfirmed) {}如果彈框關閉,那麼isConfirmed為true,進而執行if語句裡面的代碼。等等,為什麼點擊關閉按鈕之後,isConfirmed會是true呢?我們再看看關閉按鈕點擊之後執行的函數

confirm() {
    // result是一個boolean類型,這一點取決於{DialogComponent<ConfirmModel, boolean>}
    this.result = true;
    // close() 方法是由 `DialogComponent` 定義的,用於關閉模態框。在HTML模板中也有可以調用。
    this.close(); 
  }

也就是這個confirm方法,我們看到裡面有一句this.result = true;會不會是它搗的鬼。我們把this.result賦值一個字元串,然後審查一下isConfirmed有沒有改變。

在這之前我們先來確認一下原來的isConfirmed是什麼東西。

我們發現原來的isConfirmed是true,現在開始賦值為字元串“測試”。在修改result之前還要將DialogComponent<ConfirmModel, boolean>修改為DialogComponent<ConfirmModel, any>,正如上面所講,result是一個boolean類型,這一點取決於{DialogComponent<ConfirmModel, boolean>}。修改之後再審查一下。

我們發現變成測試了,這時候我們就知道了,彈框裡面的數據要返傳給父組件,可以通過result,傳遞什麼類型, 就在{DialogComponent<ConfirmModel, boolean>}做相應的類型修改。當result有賦值,即存在的時候,在app.component.ts就執行if裡面的語句,如果不存在,或者為false,就執行else裡面的語句。

四、註意

在使用該彈框的時候,有一個版本問題,如果不做任何修改,在app.module.ts導入BootstrapModalModule的時候會出現下麵的錯誤:

Metadata version mismatch for module C:/Users/ASUS/Desktop/angular/App/node_modules/ngx-bootstrap-modal/index.d.ts, found version 4,expected 3, resolving
symbol AppModulein C:/Users/ASUS/Desktop/angular/App/src/app/app.module.ts, resolving symbol AppModule
in C:/Users/ASUS/Desktop/angular/App/src/app/app.module.ts

這個錯誤只是版本的問題,嘗試一下在package.json文件裡面用"ngx-bootstrap-modal": "1.0.12"這個版本,就可以了。

詳細的彈框使用可以查看http://blog.csdn.net/qq_34551390/article/details/78270869

 

 

 



 





 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1.如果都為NaN但是他們不相等var a=NaN;var b=NaN;a==b //flase2.javascript 是一種腳本語言,可以創建伺服器端和客戶端的腳本3.javascript 中有兩個特殊數據類型 null undefined4.判斷一個是不是屬於那個類型 instanceofin ...
  • str='我是一串字元串' charAt() //獲取一整串字元串其中的某一個子字元串 取值範圍:0~字元串長度-1 alert ( str.charAt() ) //我 括弧裡面什麼都不寫時預設是第0個 alert ( str.charAt(4) ) //符 alert ( str.sharAt( ...
  • 之前我寫過一篇文章叫做《jq不會被淘汰》……而事實上它真的不會被淘汰,因為即使在mvvm框架盛行的今天,原生js的api越來越友好的今天,jq依然在用戶量上是霸主…… 但是今天我們要討論的是,拋棄jq,擁抱原生js…… 再說正題之前,我們先來看看jq比js,解決了哪些問題,哪裡更優秀 1.首當其衝是 ...
  • slice 從已有的數組中返回選定的元素。該方法不會修改數組,而是返回一個子數組。 語法:arr.slice(start,end) start: 必須,規定從何處開始選取。如果是負數,就是從尾部開始算起的位置(-1指最後一個元素,-2指倒數第二個元素); end: 可選,規定從何處結束選取。如果沒有 ...
  • 今天有了一個新需求,就是下拉框採用多選,因為以前都是用Extjs的多選框組件,領導說不好看,所以我就用了bootstrap框架實現,我現在把代碼共用一下,大家有需要的直接在hBuilder中打開,可以直接運行.下麵說一下我整合進項目中遇到的問題:1.寬高,邊距等等調整;如果想改下拉框的寬度直接修改b ...
  • 超文本標記語言,標準通用標記語言下的一個應用。“超文本”就是指頁面內可以包含圖片、鏈接,甚至音樂、程式等非文字元素。 ...
  • 簡單地記下jquery實現回車事件 全局: $(function(){document.onkeydown = function(e){ var ev = document.all ? window.event : e; if(ev.keyCode==13) { $('#FormId).submit ...
  • 如果對於正則基礎沒有太多瞭解的同學可以先看這篇文章: "初探正則表達式" 。 正則表達式是一個描述字元模式的對象, 的 類表示正則表達式, 和 都定義了方法,後者使用正則表達式進行強大的模式匹配和文本檢索於替換功能。 的正則表達式語法是 的正則表達式語法的子集。 JS中正則表達式的定義 JavaSc ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...