@Component({
...
template: '<p #bio></p>'
})
export class UserDetailsComponent {
@ViewChild('bio') bio;
}
<p> 标签的 ElementRef 对象的能力。<p> 标签被渲染为使用此组件的父视图的子元素。<p> 标签支持内容投影。<p> 标签在最终渲染中可见。如果在模板中使用了 #bio 但在类中没有使用 @ViewChild,那么 Angular 会自动隐藏带有 #bio 的 <p> 标签。DigitalOcean - viewchild-access-component
<form> 元素上添加一个名为 controls 的属性,并将 FormControl 的字符串名称赋给它,以指示应该包含哪些字段。Angular.io - Reactive Form Groups
paramMap 和 queryParamMap 有什么区别?<h2>姓名</h2>
<div *ngFor="let user of users | async"></div>
<h2>年龄</h2>
<div *ngFor="let user of users | async"></div>
<h2>性别</h2>
<div *ngFor="let user of users | async"></div>
export class OrderService {
constructor(private httpClient: HttpClient) {}
addOrder(order: Order) {
// 缺少的代码行
}
}
this.httpClient.url(this.orderUrl).post(order);this.httpClient.send(this.orderUrl, order);this.httpClient.post<Order>(this.orderUrl, order);this.httpClient.post<Order>(this.orderUrl, order).subscribe();Angular.io - Sending data to server
@Component({
selector: 'app-user-card',
. . .
})
<div app-user-card></div>。<app-user-card></app-user-card> 的第一个实例。<app-user-card></app-user-card> 的所有实例。<user-card></user-card> 的所有实例。Angular.io - Component Metadata
A
<ul>
<li [ngFor]="let productName of productNames"></li>
</ul>
B
<ul>
<li ngFor="let productName of productNames"></li>
</ul>
C
<ul>
<li *ngFor="let productName of productNames"></li>
</ul>
D
<ul>
<? for productName in productNames { ?>
<li></li>
<? } ?>
</ul>
Angular.io- Structural Directives
@Component({
selector: 'app-title-card',
template: '',
})
class TitleCardComponent {
title = 'User Data';
}
title[title]Angular.io - String Interpolation or Text Interpolation
Angular.io - Displaying a from control value
<a> 标签链接到路由?@Component({
selector: 'app-shopping-cart',
. . .
})
export class ShoppingCartComponent {
@Output() itemTotalChanged = new EventEmitter();
}
itemTotalChanged 类字段成为公共的。itemTotalChanged 类字段的方法,如:<app-shopping-cart [itemTotalChanged]="newTotal"></app-shopping-cart>。itemTotalChanged 类字段的方法,如:<app-shopping-cart (itemTotalChanged)="logNewTotal($event)"></app-shopping-cart>。Angular.io - Sending data to parent component
<div *ngIf="isVisible">Active</div>
<div [hidden]="!isVisible">Active</div>
ngIf 是另一个示例的简写。当 Angular 处理该指令时,它会向 DOM 写入一个具有 hidden 属性的 div 元素。ngIf 指令不会在 DOM 中渲染 div。hidden 属性用法在浏览器视口中隐藏 div 内容,但 div 仍然在 DOM 中。ngIf 是有效的,但 hidden 属性的使用是错误的,会抛出错误。<form #userForm="ngForm">
<input type="text" ngModel name="firstName" required />
<input type="text" ngModel name="lastName" required />
<button (click)="submit(userForm.value)">Save</button>
</form>
A
<button (click)="submit(userForm.value)" disable="userForm.invalid">Save</button>
B
<button (click)="submit(userForm.value)" [disabled]="userForm.invalid">Save</button>
C
<button (click)="submit(userForm.value)" [ngForm.disabled]="userForm.valid">Save</button>
D
<button (click)="submit(userForm.value)" *ngIf="userForm.valid">Save</button>
Angular.io - Submit the form with ngSubmit
Angular.io - ng generate options
@Component({
selector: 'app-title-card',
template: '<h1 title="User Data"> </h1>',
})
export class TitleCardComponent {
titleText = 'User Data';
}
<h1 data-title="titleText"></h1><h1 title="titleText"></h1><h1 [title]="titleText"></h1><h1 titleText></h1>Angular.io - String Interpolation
<span>Boss: </span>
{ path: 'user/:id', component: UserDetailComponent }{ url: 'user/:id', routedComponent: UserDetailComponent }{ routedPath: 'user/:id', component: UserDetailComponent }{ destination: new UserDetailComponent(), route: 'user/:id' }CodeCraft - Parameterised Routes
@Directive({
selector: '[appCallout]',
})
export class CalloutDirective {
@HostBinding('style.font-weight') fontWeight = 'normal';
@HostListener('mouseenter')
onMouseEnter() {
this.fontWeight = 'bold';
}
@HostListener('mouseleave')
onMouseLeave() {
this.fontWeight = 'normal';
}
}
<input type="text" ngModel name="firstName" required minlength="4" />
<span *ngIf="">Invalid field data</span>
<h1 #headerText>User List</h1>
<h1> 元素的内部文本Pluralsight - Template reference variable
[{ provide: FormattedLogger, useClass: Logger }][{ provide: FormattedLogger, useExisting: Logger }];
{
path: 'customers',
component: CustomerListComponent,
data: { accountSection: true }
}
ngIf 结构指令如何更改渲染的 DOM?@Component({
selector: 'app-product',
template: '<div *ngIf="product"></div>',
})
export class ProductComponent {
@Input() product;
}
<div> 充当占位符。如果 product 类字段为”真值”,<div> 将被仅 product.name 值替换;如果不是,则不会渲染任何内容。<div> 将始终被渲染,如果 product 字段为”真值”,<div> 元素将包含 product.name 值;否则,它将渲染没有值的 <div> 元素。product.name 字段值的 <div>。如果不是”真值”,渲染的 DOM 将不包含 <div> 元素。@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
bootstrap: [AppComponent],
})
export class AppModule {}
platformBrowserDynamic().bootstrapModule(AppModule);
Angular.io - The basic NgModule
{
path: ':id',
component: UserComponent,
resolve: {
user: UserResolverService
}
}
@Component({
. . .
template: '<ng-content></ng-content>'
})
export class TabsListComponent {
@ContentChildren(TabComponent) tabs;
}
<ng-content> 元素中。<ng-content> 中的任何 TabComponent 组件的能力。fixture.detectChanges() 调用的目的是什么?TestBed.configureTestingModule({
declarations: [UserCardComponent],
});
let fixture = TestBed.createComponent(UserCardComponent);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('h1').textContent).toContain(
fixture.componentInstance.title,
);
Router.navigate 方法的调用,URL 段将是什么样子?export class ToolsComponent {
constructor(private router: Router) {}
goToUser(id: number) {
this.router.navigate(['user', id]);
}
}
@Directive({
selector: ' [appHighlight] ',
})
export class HighlightDirective {
@HostBinding('class.highlighted') highlight = true;
}
<form> 元素上使用什么 Angular 表单类类型来连接它?FormArrayFormControlFormGroup所有这些答案<form [formGroup]="form">
<input type="text" formControlName="username" />
...
</form>
A
<span *ngIf="username.minLength.invalid"> Username length is not valid </span>
B
<input type="text" formControlName="username" [showMinLength]="true" />
C
<span *ngIf="form.get('username').getError('minLength') as minLengthError">
Username must be at least characters.
</span>
D
<input type="text" formControlName="username" #userName="ngModel" />
<span *ngIf="userName.errors.minlength">
Username must be at least characters.
</span>
TestBed.configureTestingModule({
declarations: [UserCardComponent],
});
let fixture = TestBed.createComponent(UserCardComponent);
fixture.componentTemplatefixture.getComponentHtml()fixture.nativeElementfixture.componentInstance.template @Component({
selector: 'app-card',
template: '<h1>Data Card</h1><ng-content></ng-content>'
})
export class CardComponent { }
@Component({
selector: 'app-bio',
template: '<ng-content></ng-content>.
})
export class BioComponent { }
// 标记用法:
<app-card><app-bio>Been around for four years.</app-bio></app-card>
A
<app-card>
<h1>Data Card</hl>
<app-bio>
Been around for four years.
</app-bio>
</app-card>
B
<h1>Data Card</h1>
<app-bio> Been around for four years. </app-bio>
C
<app-card>
<h1>Data Card</hl>
<ng-content></ng-content>
<app-bio>
Been around for four years.
<ng-content></ng-content>
</app-bio>
</app-card>
D
<app-card>
<h1>Data Card</hl>
</app-card>
@Component({
selector: 'app-user-card',
template: '<app-title-card></app-title-card><p>Jenny Smith</p>'
})
@Component({
selector: 'app-title-card',
template: '<h1>User Data</hl>'
})
// 在父组件 html 中使用 user card 组件
<app-user-card></app-user-card>
A
<app-user-card>
<app-title-card>
<h1>User Data</h1>
</app-title-card>
<p>Jenny Smith</p>
</app-user-card>
B
<h1>User Data</h1>
<p>Jenny Smith</p>
<p></p>
C
<app-user-card>
<app-title-card></app-title-card>
</app-user-card>
D
<div app-user-card>
<h1 app-title-card>User Data</h1>
<p>Jenny Smith</p>
</div>
constructor(@Inject('Logger') private logger) { }
A
providers: [Logger];
B
providers: [{ provide: 'Logger', useClass: Logger }];
C
@Injectable({
providedln: 'root'
})
D
providers: [{ provide: 'Logger' }];
export class SettingsService {
constructor(private httpClient: HttpClient) { }
...
getSettings()
{
return this.httpClient.get<Settings>(this.settingsUrl)
.pipe(
retry(3)
);
}}
getSettings 的调用将执行 get 查询。retry 操作符用于告诉 pipe 调用重试 get 查询三次。Httpclient.get 调用之后不可用。const spy = jasmine.createSpyObj('DataService', ['getUsersFromApi']);
TestBed.configureTestingModule({
providers: [UserService, { provide: DataService, useValue: spy }],
});
const userService = TestBed.get(UserService);
所有其他测试都将被忽略,包括针对这些提供者之一和未定义提供者进行断言的测试。
尽管在单个测试中针对此配置中的多个提供者进行断言时它会起作用。
@Directive({
selector: '[appTruncate]'
})
export class TruncateDirective {
. . .
}
// 期望用法示例:
<p [appTruncate]="10">Some very long text here</p>
@Input() appTruncate: number;@Output() appTruncate;constructor(maxLength: number) { }无。指令选择器不能用于将值传递给指令。HttpClient.get 请求?export class OrderService {
constructor(private httpClient: HttpClient) {}
getOrdersByYear(year: number): Observable<Order[]> {
return this.httpClient.get<Order[]>(this.ordersUrl);
}
}
return this.httpClient.get<Order[]>(this.ordersUrl, {'year': year})return this.httpClient.get<Order[]>(this.ordersUrl, year)C
const options = { params: new HttpParams().set('year', year) };
return this.httpClient.get<Order[]>(this.ordersUrl, options);
D
getOrdersByYear(year: number): Observable<Order[]> {
return this.httpClient.addParam('year', year).get<Order[]>(this.ordersUrl, year);
}
DataService 已在应用程序的提供者中注册,基于此组件的构造函数,哪个答案最能描述会发生什么?@Component({
...
})
export class OrderHistoryComponent {
constructor(private dataService: DataService) {}
...
}
OrderHistoryComponent 将拥有自己的 DataService 版本,并且永远不应使用任何现有实例。DataService 需要在类中实例化为私有字段,此代码才能完整且正常工作。OrderHistoryComponent 的新实例时,注入器将向组件构造函数的第一个参数提供 DataService 类的实例。构造函数的 dataService 参数将用于在实例上设置同名的私有实例字段。dataService 的自定义属性,可用于绑定现有的 DataService 实例。ngIf 指令完成此标记以实现 else 情况,该情况将显示文本”User is not active”:<div *ngIf="userIsActive; else inactive">Currently active!</div>
A
<div #inactive>User is not active.</div>
B
<div *ngIf="inactive">User is not active.</div>
C
<ng-template #else="inactive">
<div>User is not active.</div>
</ng-template>
D
<ng-template #inactive>
<div>User is not active.</div>
</ng-template>
A
{
path: 'users',
lazy: './users/users.module#UsersModule'
}
B
{
path: 'users',
loadChildren: () => import('./users/users.module').then(m => m.UserModule)
}
C
{
path: 'users',
loadChildren: './users/users.module#UsersModule'
}
D
{
path: 'users',
module: UsersModule
}
Angular.io - Lazy Loading Modules
export class UserFormControl implements OnInit {
...
ngOnInit() {
this.form = this.formBuilder.group({
username: this.formBuilder.control('',
[Validators.required, Validators.minLength(5), this.unique]),
)};
}
unique(control: FormControl) {
return control.value !== 'admin' ? null: {notUnique: true};
}
}
username 的 FormControl 正在配置为从允许使用的验证器中排除三个验证器。username 的 FormControl 正在配置为允许使用三个可能的验证器:required, maxLength 和名为 unique 的自定义验证器。要启用这些 validators,需要在标记的表单字段上放置验证器指令。username 的 FormControl 正在配置三个验证器:来自 Angular 的 required 和 minLength 验证器,以及名为 unique 的自定义验证器函数,该函数检查值不等于字符串 admin。@Injectable({
providedIn: 'root'
)}
export class DataService { }
export interface AppSettings {
title: string;
version: number;
}
export const APP_SETTINGS = new InjectionToken<AppSettings>('app.settings');
<form #form="ngForm">
<input type="text" ngModel="firstName" /> <input type="text" ngModel="lastName" />
<button (click)="submit()">Save</button>
</form>
prelodingStrategy 属性配置的目的是什么?RouterModule.forRoot(
...{
preloadingStrategy: PreloadAllModules,
},
);
参考:
userName 的值绑定到 h1 元素 title 属性的替代方法是什么?<h1 [title]="userName">Current user is </h1>
title="userName"title=""title="userName"async 管道在做什么?@Component({
selector: 'app-users',
template: '<div *ngFor="let user of users | async"></div>',
})
export class UsersComponent implements OnInit {
users;
constructor(private httpClient: HttpClient) {}
ngOnInit(): void {
this.users = this.httpClient.get<{ name: string }>('users');
}
}
ngFor 语句中使用。ngFor 迭代以同时支持多个用户列表。HttpClient.get 方法返回的 observable,并解包返回的值,以便可以在 ngFor 中进行迭代。users 字段中的所有用户同时渲染到 DOM。@Directive({ selector: '[appTruncate]'
})
export class TruncateDirective{ . . .
}
html <p data-directive="appTruncate">Some long text </p> html <p appTruncate>Some long text</p> html <p app-truncate>Some long text</p> html <app-truncate>Some long text</app-truncate> How to detect when an @Input() value changes in Angular?
@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
transform(value: string, maxLength: number, showEllipsis: boolean) {
const newValue = maxLength ? value.substr(0, maxLength) : value;
return showEllipsis ? '${newValue}...' : newValue;
}
}
some lo...some ltruesome long text[How do I call an Angular 2 pipe with multiple arguments?] (https://stackoverflow.com/questions/36816788/how-do-i-call-an-angular-2-pipe-with-multiple-arguments)
<div *ngIf="location">
<h1></h1>
<p></p>
</div>
A
<div *ngIf="location">
<h1></h1>
<p></p>
</div>
B
<ng-template *ngIf="location">
<h1></h1>
<p></p>
</ng-template>
C
<div *ngIf="location" [display]=" ' hidden' ">
<h1></h1>
<p></p>
</div>
D
<ng-container *ngIf="location">
<h1></h1>
<p></p>
</ng-container>
Angular unit tests - 重新检查答案
CanActivate vs Canload CanActivate 阻止访问路由,CanLoad 阻止延迟加载。
{ path: 'document', component: DocumentComponent, outlet: 'document-box'
}
<document-box> 的实例,并在路由导航时将 DocumentComponent 元素插入其中。<document-box> 元素的子元素。<router-outlet> 元素为目标,作为路由到时渲染 DocumentComponent 的位置。Angular-outlet - 重新检查答案
<div *ngFor="let item of items"> - </div>
*ngFor="let item of items; let uniqueItem"*ngFor="let item of items.distinct()"*ngFor="let item of items: let i = index"*ngFor="let item of items; trackBy: trackById"StackOverflow - How to use trackBy with ngFor
ng build --configuration=production --progress=false
Angular documentation - ng build
@Component({ selector:'app-product-name', ...
})
export class ProductNameComponent { @Input() productName: string
}
html
<input type='text' id='productName'> Dom 元素。Input()Input()useValue 提供者配置,并将其设置为现有对象或对象字面量。asValue 提供者配置属性,将其设置为 true。Configuring dependency providers
{path: 'user/:id', component: UserDetailComponent }
<form [formGroup]="form">
<input type="text" formControlName="username" />
<button type="submit" [disabled]="form. invalid">Submit</button>
</form>
<button> 元素。<form> 元素。<div [ngClass]="{ 'active-item': isActive }">Item One</div>
<div active-item>Item One</div><div class="active-item">Item One</div><div class="is-active">Item One</div><div class="active-item isActive">Item One</div><input [(ngModel)]="user.name" />
text
text
text
<span [ngClass]="{ 'active': isActive, 'can-toggle': canToggle }"> Employed </span>
A
<span class=" ">
Employed
</span>
B
<span [class.active]="isActive" [class.can-toggle]="canToggle"> Employed </span>
C
<span [styles.class.active]="isActive" [styles.class.can-toggle]="canToggle"> Employed </span>
D
<span [css.class.active]="isActive" [css.class.can-toggle]="canToggle"> Employed </span>
@Directive({
selector: '[customValidator]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: CustomValidatorDirective,
multi: true,
},
],
})
export class CustomValidatorDirective implements Validator {}
@Component({
selector: 'app-date-card',
template: '',
})
export class DateCardComponent {
currentYear() {
return new Date().getFullYear();
}
}
{{ currentYear() }}{{ component.currentYear() }}{{ currentYear }}