전역 구성
전역 구성 (Global Configuration)
많은 컴포넌트에 전역 구성 지원을 추가했어요. 전역 구성을 통해 이 컴포넌트들의 기본 동작을 정의할 수 있어요. 그러면 템플릿에 작성해야 하는 반복 코드가 줄어들어 코드가 간결해져요. 게다가 런타임에 전역 구성을 변경하는 것도 지원해요.
출처: 문서
본문
사용 방법
특정 컴포넌트에 기본 구성을 제공하려면 provideNzConfig 함수를 사용해요. NzConfig 인터페이스를 구현하는 객체를 제공해요. 예를 들어:
import { NzConfig, provideNzConfig } from 'ng-zorro-antd/core/config';
const ngZorroConfig: NzConfig = {
message: { nzTop: 120 },
notification: { nzTop: 240 }
};
export const appConfig: ApplicationConfig = {
providers: [provideNzConfig(ngZorroConfig)]
};
이러한 전역 구성은 NzConfigService라는 서비스에 주입되어 저장돼요.
템플릿 인스턴스 제공
일부 컴포넌트는 기본 매개변수로 TemplateRef<T>를 받아요.
가장 쉬운 방법 중 하나는 루트 컴포넌트에서 NzConfigService의 관련 함수를 호출하는 것이에요.
import { NzConfigService } from 'ng-zorro-antd/core/config';
export class AppComponent implements OnInit {
private nzConfigService = inject(NzConfigService);
@ViewChild('nzIndicatorTpl', { static: true })
nzIndicator!: TemplateRef<void>;
ngOnInit(): void {
this.nzConfigService.set('spin', { nzIndicator: this.nzIndicator });
}
}
하지만 이는 관심사 분리 원칙을 위반하고 AppComponent에 코드가 비대해지게 해요.
이를 해결하기 위해 NgModule 수준에서 (위에서 본) ValueProvider 대신 FactoryProvider를 사용하는 것을 권장해요.
// 템플릿 참조를 포함하는 모듈 수준 컴포넌트.
// AOT 호환성을 위해 export가 필요해요
@Component({
template: `
<ng-template #nzIndicatorTpl>
<span class="ant-spin-dot">
<nz-icon nzType="loading" />
</span>
</ng-template>
`
})
export class GlobalTemplatesComponent {
@ViewChild('nzIndicatorTpl', { static: true })
nzIndicator!: TemplateRef<void>;
}
// Factory 함수
const nzConfigFactory = (): NzConfig => {
const environmentInjector = inject(EnvironmentInjector);
const { nzIndicator } = createComponent(component, { environmentInjector }).instance;
return {
spin: {
nzIndicator
}
};
};
export const appConfig: ApplicationConfig = {
providers: [
{
// FactoryProvider
provide: NZ_CONFIG,
useFactory: nzConfigFactory
}
]
};
컴포넌트 안에서 덮어쓰기
개발자는 Dependency Injection을 사용해 특정 컴포넌트 안에서 NZ_CONFIG를 재설정할 수 있어요. 이는 바깥의 구성에는 영향을 주지 않아요.
@Component({
providers: [
// 로컬 NzConfigService 재설정
NzConfigService,
{
provide: NZ_CONFIG,
useValue: {
button: {
nzSize: 'large'
}
}
}
]
})
useFactory를 사용해 전역 구성과 로컬 구성을 결합해 적용할 수도 있어요.
참고: 컴포넌트 초기화 후 전역 구성을 변경해도 로컬 구성에는 영향을 주지 않아요.
@Component({
providers: [
// 로컬 NzConfigService 재설정
NzConfigService,
{
provide: NZ_CONFIG,
useFactory: () => {
// 전역 NzConfigService 가져오기
const globalConfig = inject(NzConfigService, { skipSelf: true }).getConfig();
const localConfig = {
select: {
nzVariant: 'borderless'
}
};
// 로컬과 전역 구성 병합
const mergedConfig = {
...globalConfig,
...localConfig
};
return mergedConfig;
},
}
]
})
구성 동적 변경
NzConfigService의 set 메서드로 특정 컴포넌트의 전역 구성을 변경할 수 있어요. 예를 들어:
import { NzConfigService } from 'ng-zorro-antd/core/config';
@Component({})
export class ChangeZorroConfigComponent {
private nzConfigService = inject(NzConfigService);
onChangeConfig() {
this.nzConfigService.set('button', { nzSize: 'large' });
}
}
모든 컴포넌트 인스턴스는 이 구성 변경에 반응해요 (독립적으로 구성되지 않은 경우).
전역 구성의 우선순위
전역 구성을 지원하는 모든 속성에 대해 우선순위는 다음과 같아요:
컴포넌트 인스턴스에 전달된 매개변수(템플릿에서 또는 service.create 같은 메서드를 통해) > 주입 토큰 NZ_CONFIG로 제공된 전역 구성 > ng-zorro-antd의 기본값
예를 들어 NzNotification 컴포넌트를 만들고 싶다고 해볼게요:
NzNotificationService.success호출 시 세 번째 매개변수로{ nzDuration: 6000 }을 전달해요- 주입 토큰
NZ_CONFIG로{ notification: { nzDuration: 5000 } }을 제공해요 ng-zorro-antd에는 기본값 4500이 있죠
결과적으로 이 특정 알림은 6000밀리초 동안 표시돼요.
전역 구성 가능한 매개변수 확인
NzConfig 인터페이스는 전역 구성이 가능한 모든 컴포넌트와 매개변수에 대한 완전한 정보를 제공해요. 각 컴포넌트의 API에서도 더 자세한 내용을 확인할 수 있어요.