Visão geral da diretiva de máscara 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

    Para começar a usar a diretiva Ignite UI for Angular Mask, primeiro você precisa instalar Ignite UI for Angular. Em um aplicativo Angular existente, digite o seguinte comando:

    ng add igniteui-angular
    

    Para obter uma introdução completa ao Ignite UI for Angular, leia o tópico de introdução.

    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 {}
    

    Alternativamente,16.0.0 você pode importar comoIgxMaskDirective uma dependência independente.

    // 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

    Personagem de máscara Descrição
    0 requer um dígito (0-9)
    9 requer um dígito (0-9) ou um espaço
    # requer um dígito (0-9), sinal de mais (+) ou menos (-)
    eu requer uma letra (aZ)
    ? requer uma letra (aZ) ou um espaço
    UM requer um alfanumérico (0-9, aZ)
    um requer um alfanumérico (0-9, aZ) ou um espaço
    & qualquer caractere do teclado (excluindo espaço)
    C qualquer caractere do teclado

    Apply Mask on Input

    No exemplo a seguir, aplicamos um número de telefone com uma máscara de ramal a uma entrada.

    <!--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>
    

    Se configurado corretamente, você deverá ver o exemplo de demonstração no seu navegador.

    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

    Além de definir uma máscara para uma entrada, você pode validar o valor inserido também. O exemplo a seguir implementa máscaras, validação e notificação para dados inválidos usando a diretiva Mask e o componente 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 {}
    

    Em seguida, adicione isto ao modelo:

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

    Você pode ver como isso funciona no exemplo anterior.

    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!

    Implemente dois pipes que irão acrescentar/remover um sinal '%' no final do valor exibido:

    @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>
    

    Como resultado, um sinal '%' deve ser acrescentado ao valor de desfoque (ou seja, quando o usuário clica fora da entrada) e será removido quando a entrada receber foco!

    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

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.