Angular 입력 그룹 구성 요소 개요

    IgxInputGroupComponent 사용하면 사용자는 입력, 선택, 텍스트 영역 등과 같은 입력 요소를 향상할 수 있습니다. 이는 텍스트, 아이콘, 버튼, 사용자 정의 유효성 검사, 플로팅 라벨 등과 같은 사용자 정의 콘텐츠를 양쪽에 추가하여 달성할 수 있습니다. 접두사, 접미사 또는 힌트.

    Angular Input Group Example

    Getting Started with Ignite UI for Angular Input Group

    Ignite UI for Angular 입력 그룹 구성 요소를 시작하려면 먼저 Ignite UI for Angular 설치해야 합니다. 기존 Angular 애플리케이션에서 다음 명령을 입력합니다.

    ng add igniteui-angular
    

    Ignite UI for Angular에 대한 전체 소개를 보려면 시작하기 항목을 읽어보세요.

    다음 단계는 IgxInputGroupModule 당신의 app.module.ts 파일.

    IgxInputGroupComponent도 작동하는 템플릿 기반 양식을 갖기 위해 Angular FormsModule에 의존합니다.

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

    또는 16.0.0부터 IgxInputGroupComponent 독립 실행형 종속성으로 가져오거나 IGX_INPUT_GROUP_DIRECTIVES 토큰을 사용하여 구성 요소와 모든 지원 구성 요소 및 지시어를 가져올 수 있습니다.

    // home.component.ts
    
    import { FormsModule } from '@angular/forms';
    import { IGX_INPUT_GROUP_DIRECTIVES, IgxIconComponent } from 'igniteui-angular';
    // import { IGX_INPUT_GROUP_DIRECTIVES, IgxIconComponent } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <igx-input-group>
            <igx-prefix>+359</igx-prefix>
            <label igxLabel for="phone">Phone</label>
            <input igxInput [(ngModel)]="value" name="phone" type="tel" maxlength="9" />
            <igx-icon igxSuffix>phone</igx-icon>
        </igx-input-group>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IGX_INPUT_GROUP_DIRECTIVES, IgxIconComponent, FormsModule]
        /* or imports: [IgxInputGroupComponent, IgxPrefixDirective, IgxLabelDirective, IgxInputDirective, IgxIconComponent, IgxSuffixDirective, FormsModule] */
    })
    export class HomeComponent {
        public value = '123456789';
    }
    

    이제 Ignite UI for Angular 모듈 또는 지시문을 가져왔으므로 igx-input-group 구성 요소 사용을 시작할 수 있습니다.

    Note

    igxInput, igxLabel, igx-prefix, igx-suffix 또는 igx-hint 지시문을 사용하려면 해당 지시문을 <igx-input-group> 컨테이너에 래핑해야 합니다.

    Using the Angular Input Group

    Label & Input

    당신은에 대해 읽을 수 있습니다 igxLabel 그리고 igxInput 지시문과 유효성 검사, 데이터 바인딩 및 API를 별도의 주제로 다룹니다. 여기.

    Prefix & Suffix

    igx-prefix 또는 igxPrefixigx-suffix 또는 igxSuffix 지시어는 HTML 요소, 문자열, 아이콘 또는 기타 구성 요소를 포함하거나 첨부할 수 있습니다. 다음 샘플에서는 문자열 접두사와 아이콘 접미사가 있는 새 입력 필드를 만듭니다.

    <igx-input-group>
        <igx-prefix>+359</igx-prefix>
        <label igxLabel for="phone">Phone</label>
        <input igxInput name="phone" type="tel" maxlength="9" />
        <igx-icon igxSuffix>phone</igx-icon>
    </igx-input-group>
    

    Hints

    igx-hint 지시문은 입력 아래에 배치된 도우미 텍스트를 제공합니다. position 속성 값에 따라 입력의 시작 부분이나 끝 부분이 될 수 있습니다. 전화 입력에 힌트를 추가해 보겠습니다.

    <igx-input-group>
        <igx-prefix>+359</igx-prefix>
        <label igxLabel for="phone">Phone</label>
        <input igxInput name="phone" type="tel" />
        <igx-suffix>
            <igx-icon>phone</igx-icon>
        </igx-suffix>
        <igx-hint position="start">Ex.: +359 888 123 456</igx-hint>
    </igx-input-group>
    

    힌트가 포함된 전화 필드는 다음과 같습니다.

    Input Types & Input Group Type Token

    입력 그룹 스타일은 igxInputGroup 구성 요소의 type 속성을 사용하여 변경할 수 있습니다. 입력 그룹 구성 요소는 line (유형이 지정되지 않은 경우 기본값), border, boxsearch 유형을 지원합니다. line, borderbox 유형은 Material Design 테마를 위해 특별히 제작되었습니다. 다른 테마로 해당 유형을 설정해도 입력 그룹의 모양에는 아무런 영향이 없습니다. 특정 유형을 선언적으로 설정하는 예:

    <igx-input-group type="border">
    

    IGX_input-group_TYPE 주입 토큰을 사용하면 모든 입력 그룹 인스턴스에 대해 애플리케이션 수준에서 유형을 지정할 수 있습니다. 모든 관련 구성 요소의 스타일을 한 번에 쉽게 지정할 수 있는 방법을 제공합니다. 유형을 설정하려면 IGX_input-group_TYPE 주입 토큰을 사용하여 DI 공급자를 생성하세요.

    providers: [{provide: IGX_input-group_TYPE, useValue: 'box' }]
    
    Note

    type 속성은 IGX_INPUT_GROUP_TYPE 보다 우선하므로 유형 속성이 명시적으로 설정된 경우 구성 요소 수준에서 토큰 값을 재정의할 수 있습니다. 대부분의 igniteui-angular 양식 컨트롤은 내부적으로 입력 그룹 구성 요소를 사용하거나 사용자 정의 템플릿을 허용합니다. 전역 토큰을 설정하면 이러한 구성 요소에도 영향을 미칩니다.

    Ignite UI for Angular type="file" 입력에 대한 스타일도 제공하고 모든 입력 그룹 유형과 테마를 지원합니다. 템플릿에 다음을 추가하기만 하면 됩니다.

    <igx-input-group>
        <input igxInput type="file" multiple />
    </igx-input-group>
    

    Input Group Theme

    입력 그룹 구성 요소는 material, fluent, bootstrapindigo-design과 같은 여러 테마를 지원합니다. theme 구성요소 초기화 중에 자동으로 설정되며 현재 사용되는 스타일시트에서 유추됩니다. 런타임 전환을 통해 애플리케이션에서 여러 테마를 지원하려는 경우 theme 입력 속성을 사용하여 테마를 명시적으로 설정할 수 있습니다.

    <igx-input-group theme="fluent">...</igx-input-group>
    

    Typed Forms

    Ignite UI for Angular Angular 14의 기본 형식인 엄격한 형식의 반응형 양식 내에서 사용할 수 있습니다. 형식화된 형식에 대한 자세한 내용을 보려면 Angular 공식 문서를 확인하세요.

    확인

    다음 샘플은 템플릿 기반 또는 반응형 양식을 사용할 때 입력 유효성 검사를 구성하는 방법을 보여줍니다.

    Template-Driven Forms

    템플릿 기반 양식 유효성 검사는 input 요소에 유효성 검사 속성(required, minlength 등)을 추가하여 수행됩니다.

    <form>
        <igx-input-group>
            <label igxLabel for="username">Username</label>
            <input igxInput name="username" type="text" required />
        </igx-input-group>
    
        <igx-input-group>
            <label igxLabel for="email">Email</label>
            <input igxInput name="email" type="email" required email />
        </igx-input-group>
    
        <igx-input-group>
            <label igxLabel for="password">Password</label>
            <input igxInput name="password" type="password" required minlength="8" />
        </igx-input-group>
    
        <button igxButton="contained" igxRipple type="submit">Submit</button>
    </form>
    

    required 속성은 레이블 옆에 별표를 추가하여 이 필드를 채워야 함을 나타냅니다. 또한 inputemailminlength와 같은 추가 유효성 검사가 적용된 경우 개발자가 최종 사용자에게 추가 확인 사항을 알릴 수 있습니다. igx-hint 지시문을 통한 요구 사항.

    다음 예제에서는 양방향 데이터 바인딩을 사용하고 ngModel을 로컬 변수로 내보내 컨트롤 상태를 검사하는 방법을 보여줍니다.

    <form #login="ngForm">
        ...
        <igx-input-group>
            <label igxLabel for="email">Email</label>
            <input igxInput name="email" type="email" [(ngModel)]="user.email" #email="ngModel" required email />
            <igx-hint *ngIf="email.errors?.email">Please enter a valid email</igx-hint>
        </igx-input-group>
    
        <igx-input-group>
            <label igxLabel for="password">Password</label>
            <input igxInput name="password" type="password"
                [(ngModel)]="user.password" #password="ngModel" required minlength="8" />
            <igx-hint *ngIf="password.errors?.minlength">Password should be at least 8 characters</igx-hint>
        </igx-input-group>
    
        <button igxButton="contained" igxRipple type="submit">Submit</button>
    </form>
    

    양식 컨트롤 중 유효하지 않은 것이 있으면 사용자는 양식을 제출할 수 없어야 합니다. 이는 양식의 상태에 따라 제출 버튼을 활성화/비활성화하여 달성할 수 있습니다.

    다음 예제에서는 ngForm 로컬 변수로 내보내 양식의 상태를 검사하는 방법을 보여줍니다.

    <form #registrationForm="ngForm">
        <igx-input-group>
            <label igxLabel for="email">Email</label>
            <input igxInput name="email" type="email" [(ngModel)]="user.email" #email="ngModel" required email />
            <igx-hint *ngIf="email.errors?.email">Please enter a valid email</igx-hint>
        </igx-input-group>
        ...
    
        <button igxButton="contained" igxRipple type="submit" [disabled]="!registrationForm.valid">Submit</button>
    </form>
    

    위 구성의 결과는 아래 샘플에서 볼 수 있습니다. 이메일 및 비밀번호 필드에 입력을 시작하면 입력한 값이 유효하지 않은 경우 igx-hint 표시되는 것을 확인할 수 있습니다. 또한 샘플은 igx-iconigx-suffix 지시문을 사용하여 비밀번호의 가시성을 전환하는 방법을 보여줍니다.

    Reactive Forms

    반응형 양식 유효성 검사는 구성 요소 클래스의 양식 제어 모델에 유효성 검사기 기능을 직접 추가하여 수행됩니다. 구성 요소 클래스에서 컨트롤을 만든 후에는 템플릿의 양식 컨트롤 요소와 연결되어야 합니다.

    public registrationForm: FormGroup<User>;
    
    constructor(fb: FormBuilder) {
        this.registrationForm = fb.group({
            username: ['', { nonNullable: true, validators: [Validators.required] }],
            email: ['', { nonNullable: true, validators: [Validators.required, Validators.email] }],
            password: ['', { nonNullable: true, validators: [Validators.required, Validators.minLength(8)] }]
        });
    }
    
    <form [formGroup]="registrationForm">
        <igx-input-group>
            <label igxLabel for="username">Username</label>
            <input igxInput name="username" type="text" formControlName="username" />
        </igx-input-group>
    
        <igx-input-group>
            <label igxLabel for="email">Email</label>
            <input igxInput name="email" type="email" formControlName="email" />
        </igx-input-group>
    
        <igx-input-group>
            <label igxLabel for="password">Password</label>
            <input igxInput name="password" type="password" formControlName="password" />
        </igx-input-group>
    
        <button igxButton="contained" igxRipple type="submit">Submit</button>
    </form>
    

    템플릿 기반 양식 샘플과 유사하게 emailminlength와 같은 추가 검증이 있는 경우 igx-hint 지시문을 사용하여 검증이 실패할 경우 최종 사용자에게 알릴 수 있습니다.

    다음 예제에서는 get 메서드를 통해 컨트롤에 액세스하고 해당 상태를 검사하는 방법을 보여줍니다. 또한 FormGroup 상태를 검사하여 제출 버튼을 활성화/비활성화하는 방법도 보여줍니다.

    public get email() {
        return this.registrationForm.get('email');
    }
    
    public get password() {
        return this.registrationForm.get('password');
    }
    
    <form [formGroup]="registrationForm">
        ...
        <igx-input-group>
            <label igxLabel for="email">Email</label>
            <input igxInput name="email" type="email" formControlName="email" />
            <igx-hint *ngIf="email.errors?.email">Please enter a valid email</igx-hint>
        </igx-input-group>
    
        <igx-input-group>
            <label igxLabel for="password">Password</label>
            <input igxInput name="password" type="password" formControlName="password" />
            <igx-hint *ngIf="password.errors?.minlength">Password should be at least 8 characters</igx-hint>
        </igx-input-group>
    
        <button igxButton="contained" igxRipple type="submit" [disabled]="!registrationForm.valid">Submit</button>
    </form>
    

    위 구성의 결과는 아래 샘플에서 볼 수 있습니다. 템플릿 기반 양식 샘플과 마찬가지로 igx-iconigx-suffix 지시문을 사용하여 비밀번호의 가시성을 전환하는 방법도 보여줍니다.

    Custom Validators

    일부 입력 필드에는 사용자 정의 유효성 검사가 필요할 수 있으며 이는 사용자 정의 유효성 검사기를 통해 달성할 수 있습니다. 값이 유효하지 않으면 유효성 검사기는 특정 오류 메시지를 표시하는 데 사용할 수 있는 오류 집합을 생성합니다.

    다음은 입력한 이메일 주소에 사전 정의된 값이 포함되어 있는지 확인하고 값이 발생하는 위치에 따라 다른 오류를 생성하는 간단한 사용자 정의 반응형 양식 유효성 검사기의 예입니다.

    public registrationForm: FormGroup<User>;
    
    constructor(fb: FormBuilder) {
        this.registrationForm = fb.group({
            email: ['', {
                nonNullable: true,
                validators: [
                    Validators.required,
                    Validators.email,
                    this.emailValidator('infragistics')
                ]
            }],
            ...
        });
    }
    
    private emailValidator(val: string): ValidatorFn {
        return (control: AbstractControl): ValidationErrors | null => {
            const value = control.value?.toLowerCase();
            const localPartRegex = new RegExp(`(?<=(${val})).*[@]`);
            const domainRegex = new RegExp(`(?<=[@])(?=.*(${val}))`);
            const returnObj: ValidatorErrors = {};
    
            if (value && localPartRegex.test(value)) {
                returnObj.localPart = true;
            }
            if (value && domainRegex.test(value)) {
                returnObj.domain = true;
            }
    
            return returnObj;
        }
    }
    

    Cross-Field Validation

    일부 시나리오에서는 한 컨트롤의 유효성 검사가 다른 컨트롤의 값에 따라 달라질 수 있습니다. 단일 사용자 정의 유효성 검사기에서 두 컨트롤을 모두 평가하려면 공통 조상 컨트롤, 즉 FormGroup에서 유효성 검사를 수행해야 합니다. 유효성 검사기는 FormGroupget 메서드를 호출하여 하위 컨트롤을 검색하고 값을 비교하며 유효성 검사에 실패하면 FormGroup에 대한 오류 집합이 생성됩니다.

    이렇게 하면 양식의 상태만 유효하지 않은 상태로 설정됩니다. 컨트롤의 상태를 설정하려면 setErrors 메서드를 사용하고 생성된 오류를 수동으로 추가할 수 있습니다. 그런 다음 유효성 검사가 성공하면 제공된 값에 대한 컨트롤의 유효성 검사를 다시 실행하는 setValue 메서드를 사용하여 오류를 제거할 수 있습니다.

    아래 예에서는 비밀번호에 이메일 주소가 포함되어서는 안 되고 반복 비밀번호가 비밀번호와 일치해야 하는 교차 필드 유효성 검사를 보여줍니다.

    private passwordValidator(): ValidatorFn {
        return (control: AbstractControl): ValidationErrors | null => {
            const email = control.get('email');
            const password = control.get('password');
            const repeatPassword = control.get('repeatPassword');
            const returnObj: ValidatorErrors = {};
    
            if (email.value
                && password.value
                && password.value.toLowerCase().includes(email.value)) {
                password.setErrors({ ...password.errors, containsEmail: true });
                returnObj.containsEmail = true;
            }
    
            if (password
                && repeatPassword
                && password.value !== repeatPassword.value) {
                repeatPassword.setErrors({ ...repeatPassword.errors, mismatch: true });
                returnObj.mismatch = true;
            }
    
            if (!returnObj.containsEmail && password.errors?.containsEmail) {
                password.setValue(password.value);
            }
    
            if (!returnObj.mismatch && repeatPassword.errors?.mismatch) {
                repeatPassword.setValue(repeatPassword.value);
            }
    
            return returnObj;
        }
    }
    

    FormGroup에 사용자 정의 유효성 검사기를 추가하려면 양식을 생성할 때 두 번째 인수로 전달되어야 합니다.

    public registrationForm: FormGroup<User>;
    
    constructor(fb: FormBuilder) {
        this.registrationForm = fb.group({
            email: ['', {
                nonNullable: true,
                validators: [
                    Validators.required,
                    Validators.email,
                    this.emailValidator('infragistics')
                ]
            }],
            ...
        },
        {
            validators: [this.passwordValidator()]
        });
    }
    

    아래 샘플은 이전 예제의 사용자 정의 emailValidator 및 교차 필드 passwordValidator와 함께 기본 제공 유효성 검사기를 사용할 수 있는 방법을 보여줍니다.

    스타일링

    입력 그룹 스타일링을 시작하기 위해 가장 먼저 해야 할 일은 스타일 파일에 index 파일을 포함시키는 것입니다.

    @use "igniteui-angular/theming" as *;
    
    // IMPORTANT: Prior to Ignite UI for Angular version 13 use:
    // @import '~igniteui-angular/lib/core/styles/themes/index';
    

    다음으로, input-group-theme 확장하고 변경하려는 매개변수를 전달하는 새 테마를 만들어야 합니다.

    $custom-input-group: input-group-theme(
      $filled-text-color: #288a54,
      $focused-text-color: #174f30,
      $idle-text-color: #288a54,
      $idle-bottom-line-color: #288a54,
      $interim-bottom-line-color: #288a54,
      $hover-bottom-line-color: #288a54,
      $focused-secondary-color: #174f30,
      $box-background: #eeeeee
    );
    

    Using CSS variables

    마지막 단계는 새로 생성된 테마를 포함하는 것입니다.

    @include css-vars($custom-input-group);
    

    Using Theme Overrides

    Internet Explorer 11과 같은 이전 브라우저의 구성 요소에 스타일을 지정하려면 CSS 변수를 지원하지 않기 때문에 입력 그룹 mixin을 사용해야 합니다.

    그러나 이전 단계에서처럼 include 문만 남겨두면 스타일이 제대로 적용되지 않습니다. 텍스트 색상은 제대로 변경되었지만 아래쪽 테두리와 배경은 동일하게 유지됩니다. 이는 우리 구성 요소가 Emulated ViewEncapsulation을 사용하고 있기 때문입니다. inputlabel 요소는 해당 뷰의 일부이므로 해당 스타일이 올바르게 적용됩니다. 반면 아래쪽 테두리는 igx-input-group 구성 요소에 의해 생성되며 구성 요소 스타일의 영향을 받지 않습니다.

    테두리 스타일을 지정하려면::ng-deep 사용하여 이 캡슐화를 penetrate 해야 합니다. 사용자 정의 테마가 다른 구성 요소로 누출되는 것을 방지하려면::ng-deep 앞에:host 선택기를 사용하여 스타일 범위를 지정해야 합니다.

    :host {
        ::ng-deep {
            @include input-group($custom-input-group);
        }
    }
    

    Demo

    API References

    Theming Dependencies

    Additional Resources

    관련 주제:

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