Bài 32: Modal Tìm hiểu ion-modal, ion-backdrop

Bài 32: Modal Tìm hiểu ion-modal, ion-backdrop

 


 ion-modal

Modal là một hộp thoại xuất hiện trên đầu nội dung của ứng dụng và phải được ứng dụng loại bỏ trước khi tương tác có thể tiếp tục. Nó hữu ích như một thành phần chọn khi có nhiều tùy chọn để chọn, hoặc khi lọc các mục trong danh sách, cũng như nhiều trường hợp sử dụng khác.




Dismissing

mode có thể bị loại bỏ sau khi tạo bằng cách gọi dismiss()phương thức trên bộ điều khiển phương thức. Các onDidDismisschức năng có thể được gọi để thực hiện một hành động sau khi phương thức được sa thải.

Customization

Modal sử dụng tính năng đóng gói theo phạm vi, có nghĩa là nó sẽ tự động mở rộng phạm vi CSS của mình bằng cách nối mỗi kiểu với một lớp bổ sung trong thời gian chạy. Ghi đè các bộ chọn theo phạm vi trong CSS yêu cầu một bộ chọn có higher specificity.

Chúng tôi khuyên bạn nên chuyển một lớp tùy chỉnh vào cssClass trong create phương thức và sử dụng lớp đó để thêm các kiểu tùy chỉnh vào máy chủ và các phần tử bên trong. Thuộc tính này cũng có thể chấp nhận nhiều lớp được phân tách bằng dấu cách. Xem Sử dụng cho một ví dụ về cách vượt qua một lớp bằng cách sử dụng cssClass.

 /* DOES NOT WORK - not specific enough */

.modal-wrapper {
  background: #222;
}

/* Works - pass "my-custom-class" in cssClass to increase specificity */
.my-custom-class .modal-wrapper {
  background: #222;
}

Bất kỳ trong số những điều đã xác định Thuc tính tùy chnh CSS có thể được sử dụng để tạo kiểu cho Phương thức mà không cần nhắm mục tiêu đến các phần tử riêng lẻ:

.my-custom-class {
  --background: #222;
}

Usage

import { Component } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { ModalPage } from '../modal/modal.page';

@Component({
  selector: 'modal-example',
  templateUrl: 'modal-example.html',
  styleUrls: ['./modal-example.css']
})
export class ModalExample {
  constructor(public modalController: ModalController) {

  }

  async presentModal() {
    const modal = await this.modalController.create({
      component: ModalPage,
      cssClass: 'my-custom-class'
    });
    return await modal.present();
  }
}
CopyCopied
import { Component, Input } from '@angular/core';

@Component({
  selector: 'modal-page',
})
export class ModalPage {

  constructor() {}

}
customElements.define('modal-page', class extends HTMLElement {
  connectedCallback() {
    this.innerHTML = `
<ion-header>
  <ion-toolbar>
    <ion-title>Modal Header</ion-title>
    <ion-buttons slot="primary">
      <ion-button onClick="dismissModal()">
        <ion-icon slot="icon-only" name="close"></ion-icon>
      </ion-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
  Modal Content
</ion-content>`;
  }
});

function presentModal() {
  // create the modal with the `modal-page` component
  const modalElement = document.createElement('ion-modal');
  modalElement.component = 'modal-page';
  modalElement.cssClass = 'my-custom-class';

  // present the modal
  document.body.appendChild(modalElement);
  return modalElement.present();
}
/* Using with useIonModal Hook */ 

import React, { useState } from 'react';
import { IonButton, IonContent, IonPage, useIonModal } from '@ionic/react';

const Body: React.FC<{
  count: number;
  onDismiss: () => void;
  onIncrement: () => void;
}> = ({ count, onDismiss, onIncrement }) => (
  <div>
    count: {count}
    <IonButton expand="block" onClick={() => onIncrement()}>
      Increment Count
    </IonButton>
    <IonButton expand="block" onClick={() => onDismiss()}>
      Close
    </IonButton>
  </div>
);

const ModalExample: React.FC = () => {
  const [count, setCount] = useState(0);

  const handleIncrement = () => {
    setCount(count + 1);
  };

  const handleDismiss = () => {
    dismiss();
  };

  /**
   * First parameter is the component to show, second is the props to pass
   */
  const [present, dismiss] = useIonModal(Body, {
    count,
    onDismiss: handleDismiss,
    onIncrement: handleIncrement,
  });

  return (
    <IonPage>
      <IonContent fullscreen>
        <IonButton
          expand="block"
          onClick={() => {
            present({
              cssClass: 'my-class',
            });
          }}
        >
          Show Modal
        </IonButton>
        <div>Count: {count}</div>
      </IonContent>
    </IonPage>
  );
};
CopyCopied
/* Using with IonModal Component */

import React, { useState } from 'react';
import { IonModal, IonButton, IonContent } from '@ionic/react';

export const ModalExample: React.FC = () => {
  const [showModal, setShowModal] = useState(false);

  return (
    <IonContent>
      <IonModal isOpen={showModal} cssClass='my-custom-class'>
        <p>This is modal content</p>
        <IonButton onClick={() => setShowModal(false)}>Close Modal</IonButton>
      </IonModal>
      <IonButton onClick={() => setShowModal(true)}>Show Modal</IonButton>
    </IonContent>
  );
};
import { Component, h } from '@stencil/core';

import { modalController } from '@ionic/core';

@Component({
  tag: 'modal-example',
  styleUrl: 'modal-example.css'
})
export class ModalExample {
  async presentModal() {
    const modal = await modalController.create({
      component: 'page-modal',
      cssClass: 'my-custom-class'
    });
    await modal.present();
  }
}
CopyCopied
import { Component, h } from '@stencil/core';

@Component({
  tag: 'page-modal',
  styleUrl: 'page-modal.css',
})
export class PageModal {
  render() {
    return [
      <ion-list>
        <ion-item>
          <ion-label>Documentation</ion-label>
        </ion-item>
        <ion-item>
          <ion-label>Feedback</ion-label>
        </ion-item>
        <ion-item>
          <ion-label>Settings</ion-label>
        </ion-item>
      </ion-list>
    ];
  }
}
<template>
  <ion-header>
    <ion-toolbar>
      <ion-title>{{ title }}</ion-title>
    </ion-toolbar>
  </ion-header>
  <ion-content class="ion-padding">
    {{ content }}
  </ion-content>
</template>

<script>
import { IonContent, IonHeader, IonTitle, IonToolbar } from '@ionic/vue';
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'Modal',
  props: {
    title: { type: String, default: 'Super Modal' },
  },
  data() {
    return {
      content: 'Content',
    }
  },
  components: { IonContent, IonHeader, IonTitle, IonToolbar }
});
</script>
CopyCopied
<template>
  <ion-page>
    <ion-content class="ion-padding">
      <ion-button @click="openModal">Open Modal</ion-button>
    </ion-content>
  </ion-page>
</template>

<script>
import { IonButton, IonContent, IonPage, modalController } from '@ionic/vue';
import Modal from './modal.vue'

export default {
  components: { IonButton, IonContent, IonPage },
  methods: {
    async openModal() {
      const modal = await modalController
        .create({
          component: Modal,
          cssClass: 'my-custom-class',
          componentProps: {
            title: 'New Title'
          },
        })
      return modal.present();
    },
  },
}
</script>
Các nhà phát triển cũng có thể sử dụng thành phần này trực tiếp trong mẫu của họ:

<template>
  <ion-button @click="setOpen(true)">Show Modal</ion-button>
  <ion-modal
    :is-open="isOpenRef"
    css-class="my-custom-class"
    @didDismiss="setOpen(false)"
  >
    <Modal :data="data"></Modal>
  </ion-modal>
</template>

<script>
import { IonModal, IonButton } from '@ionic/vue';
import { defineComponent, ref } from 'vue';
import Modal from './modal.vue'

export default defineComponent({
  components: { IonModal, IonButton, Modal },
  setup() {
    const isOpenRef = ref(false);
    const setOpen = (state: boolean) => isOpenRef.value = state;
    const data = { content: 'New Content' };
    return { isOpenRef, setOpen, data }
  }
});
</script>

Properties


animated

Description

If true, the modal will animate.

Attributeanimated
Typeboolean
Defaulttrue

backdropDismiss

Description

If true, the modal will be dismissed when the backdrop is clicked.

Attributebackdrop-dismiss
Typeboolean
Defaulttrue

component

Description

The component to display inside of the modal.

Attributecomponent
TypeFunction | HTMLElement | null | string

componentProps

Description

The data to pass to the modal component.

Typeundefined | { [key: string]: any; }

cssClass

Description

Additional classes to apply for custom CSS. If multiple classes are provided they should be separated by spaces.

Attributecss-class
Typestring | string[] | undefined

enterAnimation

Description

Animation to use when the modal is presented.

Type((baseEl: any, opts?: any) => Animation) | undefined

keyboardClose

Description

If true, the keyboard will be automatically dismissed when the overlay is presented.

Attributekeyboard-close
Typeboolean
Defaulttrue

leaveAnimation

Description

Animation to use when the modal is dismissed.

Type((baseEl: any, opts?: any) => Animation) | undefined

mode

Description

The mode determines which platform styles to use.

Attributemode
Type"ios" | "md"

presentingElement

Description

The element that presented the modal. This is used for card presentation effects and for stacking multiple modals on top of each other. Only applies in iOS mode.

TypeHTMLElement | undefined

showBackdrop

Description

If true, a backdrop will be displayed behind the modal.

Attributeshow-backdrop
Typeboolean
Defaulttrue

swipeToClose

Description

If true, the modal can be swiped to dismiss. Only applies in iOS mode.

Attributeswipe-to-close
Typeboolean
Defaultfalse

Events

NameDescription
ionModalDidDismissEmitted after the modal has dismissed.
ionModalDidPresentEmitted after the modal has presented.
ionModalWillDismissEmitted before the modal has dismissed.
ionModalWillPresentEmitted before the modal has presented.

Methods

dismiss

Description

Dismiss the modal overlay after it has been presented.

Signaturedismiss(data?: any, role?: string | undefined) => Promise<boolean>

onDidDismiss

Description

Returns a promise that resolves when the modal did dismiss.

SignatureonDidDismiss<T = any>() => Promise<OverlayEventDetail<T>>

onWillDismiss

Description

Returns a promise that resolves when the modal will dismiss.

SignatureonWillDismiss<T = any>() => Promise<OverlayEventDetail<T>>

present

Description

Present the modal overlay after it has been created.

Signaturepresent() => Promise<void>

CSS Custom Properties

NameDescription
--backdrop-opacityOpacity of the backdrop
--backgroundBackground of the modal content
--border-colorBorder color of the modal content
--border-radiusBorder radius of the modal content
--border-styleBorder style of the modal content
--border-widthBorder width of the modal content
--heightHeight of the modal
--max-heightMaximum height of the modal
--max-widthMaximum width of the modal
--min-heightMinimum height of the modal
--min-widthMinimum width of the modal
--widthWidth of the modal

ion-backdrop

 Backdrops là thành phần toàn màn hình phủ lên các thành phần khác. Chúng hữu ích đằng sau các thành phần chuyển tiếp lên trên nội dung khác và có thể được sử dụng để loại bỏ thành phần đó.




Usage

<!-- Default backdrop -->
<ion-backdrop></ion-backdrop>

<!-- Backdrop that is not tappable -->
<ion-backdrop tappable="false"></ion-backdrop>

<!-- Backdrop that is not visible -->
<ion-backdrop visible="false"></ion-backdrop>

<!-- Backdrop with propagation -->
<ion-backdrop stopPropagation="false"></ion-backdrop>

<!-- Backdrop that sets dynamic properties -->
<ion-backdrop
  [tappable]="enableBackdropDismiss"
  [visible]="showBackdrop"
  [stopPropagation]="shouldPropagate">
</ion-backdrop>
CopyCopied
import { Component } from '@angular/core';

@Component({
  selector: 'backdrop-example',
  templateUrl: 'backdrop-example.html',
  styleUrls: ['./backdrop-example.css'],
})
export class BackdropExample {
  enableBackdropDismiss = false;
  showBackdrop = false;
  shouldPropagate = false;
}
<!-- Default backdrop -->
<ion-backdrop></ion-backdrop>

<!-- Backdrop that is not tappable -->
<ion-backdrop tappable="false"></ion-backdrop>

<!-- Backdrop that is not visible -->
<ion-backdrop visible="false"></ion-backdrop>

<!-- Backdrop with propagation -->
<ion-backdrop stop-propagation="false"></ion-backdrop>

<!-- Backdrop that sets dynamic properties -->
<ion-backdrop id="customBackdrop"></ion-backdrop>
CopyCopied
var backdrop = document.getElementById('customBackdrop');
backdrop.visible = false;
backdrop.tappable = false;
backdrop.stopPropagation = false;
import React from 'react';
import { IonBackdrop, IonContent } from '@ionic/react';

export const BackdropExample: React.FC = () => (
  <IonContent>
    {/*-- Default backdrop --*/}
    <IonBackdrop />

    {/*-- Backdrop that is not tappable --*/}
    <IonBackdrop tappable={false} />

    {/*-- Backdrop that is not visible --*/}
    <IonBackdrop visible={false} />

    {/*-- Backdrop with propagation --*/}
    <IonBackdrop stopPropagation={false} />

    <IonBackdrop tappable={true} visible={true} stopPropagation={true} />
  </IonContent>
);
import { Component, h } from '@stencil/core';

@Component({
  tag: 'backdrop-example',
  styleUrl: 'backdrop-example.css'
})
export class BackdropExample {
  render() {
    const enableBackdropDismiss = false;
    const showBackdrop = false;
    const shouldPropagate = false;

    return [
      // Default backdrop
      <ion-backdrop></ion-backdrop>,

      // Backdrop that is not tappable
      <ion-backdrop tappable={false}></ion-backdrop>,

      // Backdrop that is not visible
      <ion-backdrop visible={false}></ion-backdrop>,

      // Backdrop with propagation
      <ion-backdrop stopPropagation={false}></ion-backdrop>,

      // Backdrop that sets dynamic properties
      <ion-backdrop
        tappable={enableBackdropDismiss}
        visible={showBackdrop}
        stopPropagation={shouldPropagate}>
      </ion-backdrop>
    ];
  }
}
<template>
  <!-- Default backdrop -->
  <ion-backdrop></ion-backdrop>

  <!-- Backdrop that is not tappable -->
  <ion-backdrop tappable="false"></ion-backdrop>

  <!-- Backdrop that is not visible -->
  <ion-backdrop visible="false"></ion-backdrop>

  <!-- Backdrop with propagation -->
  <ion-backdrop stop-propagation="false"></ion-backdrop>

  <!-- Backdrop that sets dynamic properties -->
  <ion-backdrop
    :tappable="enableBackdropDismiss"
    :visible="showBackdrop"
    :stop-propagation="shouldPropagate">
  </ion-backdrop>
</template>

<script>
import { IonBackdrop } from '@ionic/vue';
import { defineComponent } from 'vue';

export default defineComponent({
  components: { IonBackdrop },
  setup() {
    return {
      enableBackdropDismiss: true,
      showBackdrop: true,
      shouldPropagate: true
    }
  }
});
</script>

Properties

stopPropagation

Description

Nếu true, phông nền sẽ ngừng truyền khi nhấn.

Attributestop-propagation
Typeboolean
Defaulttrue

tappable

Description

Nếu true, phông nền sẽ có thể được nhấp và sẽ phát ra ionBackdropTapsự kiện.

Attributetappable
Typeboolean
Defaulttrue

visible

Description

Nếu true, phông nền sẽ hiển thị.

Attributevisible
Typeboolean
Defaulttrue

Events

NameDescription
ionBackdropTapPhát ra(Emitted ) khi chạm vào phông nền.

Đăng nhận xét

0 Nhận xét

myadcash