Descripción general de la directiva de mascarillas de 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 comenzar con la directiva Ignite UI for Angular Mask, primero debe instalar Ignite UI for Angular. En una aplicación Angular existente, escriba el siguiente comando:
ng add igniteui-angular
Para obtener una introducción completa al Ignite UI for Angular, lea el tema de introducción.
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 puedes importarlosIgxMaskDirective como una dependencia independiente.
// 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
| Personaje de máscara | Descripción |
|---|---|
| 0 | requiere un dígito (0-9) |
| 9 | requiere un dígito (0-9) o un espacio |
| # | requiere un dígito (0-9), un signo más (+) o menos (-) |
| l | requiere una letra (aZ) |
| ? | requiere una letra (aZ) o un espacio |
| A | requiere un carácter alfanumérico (0-9, aZ) |
| a | requiere un carácter alfanumérico (0-9, aZ) o un espacio |
| & | cualquier carácter del teclado (excluyendo el espacio) |
| C | cualquier carácter del teclado |
Apply Mask on Input
En el siguiente ejemplo, aplicamos un número de teléfono con una máscara de extensión a una 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>
Si está configurado correctamente, debería ver la muestra de demostración en su 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
Además de configurar una máscara para una entrada, también puede validar el valor ingresado. El siguiente ejemplo implementa máscaras, validación y notificación de datos no válidos utilizando la directiva Mask y el 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 {}
Luego agregue esto a la plantilla:
<igx-input-group>
<input igxInput [igxMask]="'###-##-####'" [igxTextSelection]="true"/>
</igx-input-group>
Puedes ver cómo funciona esto en el ejemplo 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 dos tuberías que agregarán/eliminarán un signo '%' al final del valor mostrado:
@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, se debe agregar un signo '%' al valor en desenfoque (es decir, cuando el usuario hace clic fuera de la entrada) y se eliminará una vez que la entrada se enfoque.
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
Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.