Angular 마스크 지침 개요

    By applying the igxMask directive on a text input field, the developer can control user input and format the visible value, based on configurable mask rules. It provides different input options and ease in use and configuration.

    Angular Mask Example

    Getting Started with Ignite UI for Angular Mask

    Ignite UI for Angular Mask 지시문을 시작하려면 먼저 Ignite UI for Angular 설치해야 합니다. 기존 Angular 애플리케이션에서 다음 명령을 입력합니다.

    ng add igniteui-angular
    

    Ignite UI for Angular에 대한 전체 소개는 시작 항목을 참조하십시오.

    The next step is to import the IgxMaskModule and IgxInputGroupModule in your app.module.ts file.

    Note

    igxMask directive is used on an input of type text.

    // app.module.ts
    
    ...
    import { IgxMaskModule } from 'igniteui-angular/input-group';
    import { IgxInputGroupModule } from 'igniteui-angular/input-group';
    // import { IgxMaskModule, IgxInputGroupModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        ...
        imports: [..., IgxMaskModule, IgxInputGroupModule],
        ...
    })
    export class AppModule {}
    

    또는16.0.0 독립 실행형 의존성으로 가져올IgxMaskDirective 수도 있습니다.

    // home.component.ts
    
    import { IgxMaskDirective, IGX_INPUT_GROUP_DIRECTIVES } from 'igniteui-angular/input-group';
    // import { IgxMaskDirective, IGX_INPUT_GROUP_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <igx-input-group>
            <igx-prefix>
                <igx-icon>phone</igx-icon>
            </igx-prefix>
            <label igxLabel>Phone</label>
            <input igxInput type="text" [igxMask]="'(####) 00-00-00 Ext. 9999'"/>
        </igx-input-group>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IgxMaskDirective, IGX_INPUT_GROUP_DIRECTIVES]
    })
    export class HomeComponent {}
    

    Now that you have the Ignite UI for Angular Mask module or directive imported, you can start using the igxMask directive.

    Using the Angular Mask

    Supported Built-in Mask Rules

    마스크 캐릭터 설명
    0 숫자(0-9)가 필요합니다.
    9 숫자(0-9) 또는 공백이 필요합니다.
    # 숫자(0-9), 더하기(+) 또는 빼기(-) 기호가 필요합니다.
    문자(aZ)가 필요합니다.
    ? 문자(aZ) 또는 공백이 필요합니다.
    영숫자(0-9, aZ)가 필요합니다.
    영숫자(0-9, aZ) 또는 공백이 필요합니다.
    & 모든 키보드 문자(공백 제외)
    모든 키보드 문자

    Apply Mask on Input

    다음 예에서는 확장 마스크가 있는 전화번호를 입력에 적용합니다.

    <!--sample.component.html-->
    
    <igx-input-group>
        <igx-prefix>
            <igx-icon>phone</igx-icon>
        </igx-prefix>
        <label igxLabel>Phone</label>
        <input igxInput type="text" [igxMask]="'(####) 00-00-00 Ext. 9999'"/>
    </igx-input-group>
    

    올바르게 구성되면 브라우저에 데모 샘플이 표시됩니다.

    Note

    The IgxMaskDirective supports IME input and updates the mask when composition ends.

    Bind to Formatted/Raw Value

    Use the includeLiterals input to configure which input value (formatted or raw) to bind in your form when a specific mask is applied. By default, includeLiterals is set to false and the raw value is used.

    <!--sample.component.html-->
    
    <igx-switch [(ngModel)]="includeLiterals" (change)="clear()">
        Include Literals
    </igx-switch>
    
    <igx-input-group>
        <label igxLabel>
            Social Security Number
        </label>
        <input #ssn name="socialSecurityNumber" type="text"
            igxInput
            [igxMask]="'###-##-####'"
            [(ngModel)]="socialSecurityNumber"
            [includeLiterals]="includeLiterals" />
    </igx-input-group>
    
    <p *ngIf="socialSecurityNumber.length > 0">Value: {{ socialSecurityNumber }}</p>
    
    // sample.component.ts
    
    public socialSecurityNumber: string = '123-45-6789';
    public includeLiterals: boolean = true;
    
    public clear() {
        if (this.includeLiterals === false){
            this.socialSecurityNumber = '123-45-6789';
        } else {
            this.socialSecurityNumber = '';
        }
    }
    

    Validate Masked Values

    입력에 마스크를 설정하는 것 외에도 입력한 값의 유효성을 검사할 수도 있습니다. 다음 예제에서는 Mask 지시문과 Snack Bar 구성 요소를 사용하여 잘못된 데이터에 대한 마스크, 유효성 검사 및 알림을 구현합니다.

    <!--sample.component.html-->
    
    <igx-input-group>
        <label igxLabel for="birthday">Birthday</label>
        <input igxInput #dateInput [igxMask]="'00/00/0000'" [igxTextSelection]="true" name="birthday" type="text"
            (blur)="validateDate(dateInput, snackbar)" />
    </igx-input-group>
    
    <igx-snackbar #snackbar></igx-snackbar>
    
    // sample.component.ts
    
    public validateDate(dateInput, snackbar) {
        if (!this.isDateValid(dateInput.value)) {
            this.notify(snackbar, 'Invalid Date', dateInput);
        }
    }
    
    private isDateValid(date) {
        return (new Date(date).toLocaleString() !== 'Invalid Date');
    }
    
    private notify(snackbar, message, input) {
        snackbar.message = message;
        snackbar.show();
    }
    

    Text Selection

    You can force the component to select all of the input text on focus using igxTextSelection. Find more info on igxTextSelection at Label & Input.

    Import the IgxTextSelectionModule in your app.module.ts file:

    ...
    import { ..., IgxTextSelectionModule } from 'igniteui-angular/input-group';
    // import { ..., IgxTextSelectionModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        ...
        imports: [..., IgxTextSelectionModule]
        ...
    })
    export class AppModule {}
    

    그런 다음 템플릿에 다음을 추가합니다.

    <igx-input-group>
        <input igxInput [igxMask]="'###-##-####'" [igxTextSelection]="true"/>
    </igx-input-group>
    

    이전 샘플에서 이것이 어떻게 작동하는지 확인할 수 있습니다.

    Note

    In order for the component to work properly, it is crucial to set igxTextSelection after the igxMask directive. The reason for this is both directives operate on the input focus event so text selection should happen after the mask is set.

    Apply additional formatting on focus and blur

    In addition to the default mask behavior, the user can implement his own custom pipes and take advantage of the focusedValuePipe and displayValuePipe input properties, to transform the value to a desired output when the input gets or loses focus. This will not affect the underlying model value. Let's demonstrate how this can be achieved!

    표시된 값 끝에 '%' 기호를 추가/제거하는 두 개의 파이프를 구현합니다.

    @Pipe({ name: 'displayFormat' })
    export class DisplayFormatPipe implements PipeTransform {
        public transform(value: any): string {
            if (value !== null && value !== undefined) {
                value = value.toString().trim();
                if (!value.endsWith('%')) {
                    value += ' %';
                }
            }
            return value;
        }
    }
    
    @Pipe({ name: 'inputFormat' })
    export class InputFormatPipe implements PipeTransform {
        public transform(value: any): string {
            if (value !== null && value !== undefined) {
                value = value.toString().replace(/%/g, '').trim();
            }
            return value;
        }
    }
    

    Pass an instance of each pipe to the focusedValuePipe and displayValuePipe input properties as follows:

    public value = 100;
    public displayFormat = new DisplayFormatPipe();
    public inputFormat = new InputFormatPipe();
    
    <igx-input-group>
        <label igxLabel>Increase</label>
        <input
            igxInput
            type="text"
            [(ngModel)]="value"
            [igxMask]="'000'"
            [igxTextSelection]="true"
            [focusedValuePipe]="inputFormat"
            [displayValuePipe]="displayFormat"
        />
    </igx-input-group>
    

    결과적으로 '%' 기호는 흐림 값(예: 사용자가 입력 외부를 클릭할 때)에 추가되어야 하며 입력에 초점이 맞춰지면 제거됩니다!

    Adding a placeholder

    The user can also take advantage of the placeholder input property, which serves the purpose of the native input placeholder attribute. If no value is provided for the placeholder, the value set for the mask is used.

    value = null;
    
    <igx-input-group>
        <label igxLabel>Date</label>
        <input igxInput
        type="text"
        [(ngModel)]="value"
        [igxMask]="'00/00/0000'"
        [placeholder]="'dd/mm/yyyy'"/>
    </igx-input-group>
    

    API References

    Additional Resources

    우리 커뮤니티는 활동적이며 항상 새로운 아이디어를 환영합니다.