Angular 입력 그룹 구성 요소 개요

    사용자는IgxInputGroupComponent 입력, 선택, 텍스트 영역 등과 같은 입력 요소를 향상시킬 수 있습니다. 이는 텍스트, 아이콘, 버튼, 맞춤 검증, 플로팅 라벨 등과 같은 맞춤 콘텐츠를 접두사, 접미사, 힌트 등으로 양쪽에 추가함으로써 달성할 수 있습니다.

    Angular 입력 그룹 예제

    Ignite UI for Angular 시작하기

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

    ng add igniteui-angular
    

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

    다음 단계는 다음 단계를 가져오는 것입니다.IgxInputGroupModule 당신의 app.module.ts 파일.

    참고로IgxInputGroupComponent Angular에 따라 다르다 양식 모듈 작동하는 템플릿 기반 폼을 가지기 위해:

    // 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 사용을 시작할 수 있습니다.

    메모

    어떤 지침igxInputigxLabeligx-prefixigx-suffixigx-hint 이든 사용하려면 컨테이너에 싸<igx-input-group>야 합니다.

    Angular 입력 그룹 사용

    라벨 및 입력

    You can read about the igxLabel and igxInput directives as well as their validation, data binding and API in a separate topic here.

    접두사 접미사

    또는igx-prefixigxPrefixigx-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>
    

    힌트

    지시문은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>
    

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

    입력 유형 및 입력 그룹 유형 토큰

    입력 그룹 스타일은 컴포넌트type의 속성을 사용하여igxInputGroup 변경할 수 있습니다. 입력 그룹 컴포넌트는 다음과 같은 유형을 지원합니다:line (유형이 지정되지 않은 경우 기본값),border,box 그리고search theline,,border andbox types는 주제에 맞게Material Design 특별히 만들어졌습니다. 다른 테마와 함께 그 타입들을 설정해도 입력 그룹의 모습에는 아무런 영향이 없습니다. 특정 타입을 선언적으로 설정하는 예시:

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

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

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

    속성은type​ ​IGX_INPUT_GROUP_TYPE 보다 우선하므로, 타입 속성이 명시적으로 설정되면 구성 요소 수준에서 토큰 값을 덮어쓸 수 있습니다. 대부분의 폼 컨트롤은igniteui-angular 내부적으로 입력 그룹 컴포넌트를 사용하거나 사용자 지정 템플릿을 허용합니다. 글로벌 토큰 설정도 이 구성 요소들에 영향을 미칩니다.

    Ignite UI for Angular 입력type="file" 스타일링도 제공하며 모든 입력 그룹 유형과 테마를 지원합니다. 템플릿에 이 내용을 추가하면 됩니다:

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

    입력 그룹 테마

    입력 그룹 구성 요소는 여러 주제를 지원합니다 -material,fluent,bootstrap,, 그리고indigo-designtheme 컴포넌트 초기화 중에 자동으로 설정되며, 현재 사용 중인 스타일시트에서 추론됩니다. 런타임 전환으로 여러 테마를 지원할 계획이라면, Input 속성으로theme 테마를 명시적으로 설정할 수 있습니다.

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

    입력된 양식

    Ignite UI for Angular Angular 14부터 기본적으로 제공되는 엄격하게 유형이 지정된 반응형 폼 내부에서 사용할 수 있습니다. 유형이 지정된 폼에 대해 자세히 알아보려면 Angular 공식 문서를 확인하세요.

    확인

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

    템플릿 기반 양식

    템플릿 기반 폼 검증은 요소에required 검증 속성(예:minlengthinput 등)을 추가함으로써 이루어집니다.

    <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 라벨 옆에 별표를 붙여 이 필드를 채워야 함을 나타냅니다. 또한, 추가적인 검증(예:input andemail)이 적용될 경우minlength, 개발자는 지시를 통해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-icon 디렉티브를 사용하여igx-suffix 비밀번호의 가시성을 토글하는 방법을 보여줍니다.

    반응형 양식

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

    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>
    

    템플릿 기반 폼 샘플과 유사하게, andemail와 같은minlength 추가 검증이 있을 때,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-icon 디렉티브를 사용하여igx-suffix 비밀번호의 가시성을 토글하는 방법도 보여줍니다.

    사용자 정의 유효성 검사기

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

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

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

    필드 간 검증

    어떤 경우에는 한 통제의 검증이 다른 통제의 값에 달려 있을 수 있습니다. 단일 맞춤형 검증기에서 두 통제를 평가하려면 공통 조상 통제, 즉FormGroup 검증기는 theFormGroup 메서드를get 호출하여 자식 제어를 불러와, 값을 비교하고, 검증이 실패하면 오류 집합이 생성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(
        $box-background: #57a5cd,
        $border-color: #57a5cd,
    );
    

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

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

    Demo

    메모

    페이지에 여러 입력 그룹 유형(예:boxborderline, 또는search)이 포함되어 있다면, 테마 변수를 특정 입력 그룹 유형에 맞게 스코핑하는 것이 좋습니다.
    예를 들어:
    박스 스타일 입력을 스타일링할 때 사용.igx-input-group--box 하세요. 검색 입력을 타겟팅할 때 사용됩니다.igx-input-group--search. 이렇게 하면 서로 다른 입력 유형 간 스타일 충돌을 방지할 수 있습니다. 예를 들어, 어두운$box-background 색을 전역적으로 설정하면 경계선이나 선 입력의 경계가 보이지 않게 되어(보통 흰색으로 보일 수 있습니다).

    API 참조

    테마 종속성

    추가 리소스

    관련 주제:

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