angular8 Renderer2 获取div子级标签
时间: 2023-05-23 08:03:10 浏览: 67
可以使用Renderer2的query方法来获取div子级标签。具体代码如下:
```typescript
import { Component, Renderer2, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div #myDiv>
<p>子级标签1</p>
<p>子级标签2</p>
</div>
`,
})
export class AppComponent {
@ViewChild('myDiv', { static: true }) myDiv: ElementRef;
constructor(private renderer: Renderer2) {}
ngAfterViewInit() {
const divEls = this.renderer.selectores('p', this.myDiv.nativeElement);
console.log(divEls);
}
}
```
这段代码中,我们通过@ViewChild获取了模板中的div元素,并在ngAfterViewInit生命周期钩子中通过Renderer2的selectores方法来获取div子级的所有p标签。
相关问题
angular 的Renderer2修改动画属性
可以使用Renderer2的setProperty方法来修改动画属性,例如:
import { Component, Renderer2, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private renderer: Renderer2, private el: ElementRef) {}
changeAnimation() {
const element = this.el.nativeElement.querySelector('.my-element');
this.renderer.setProperty(element, 'animation-duration', '2s');
}
}
在上面的代码中,我们使用Renderer2的setProperty方法来将动画持续时间修改为2秒。注意,我们需要使用ElementRef来获取元素的引用。
Angular 路由添加子级路由
在 Angular 中,可以通过添加子级路由来实现嵌套路由。以下是添加子级路由的步骤:
1. 在父级路由的定义中,添加一个 `children` 数组。
```typescript
const routes: Routes = [
{
path: 'parent',
component: ParentComponent,
children: [
{
path: 'child',
component: ChildComponent
},
// 添加更多子级路由
]
},
// 添加更多路由
];
```
2. 在子级路由的定义中,指定子级路由的路径和对应的组件。
```typescript
{
path: 'child',
component: ChildComponent
}
```
3. 在父级组件的模板中,添加一个 `router-outlet` 元素,用于显示子级路由的组件。
```html
<router-outlet></router-outlet>
```
4. 使用父级路由的路径和子级路由的路径组合成完整的路由路径,即可访问子级路由。
```html
<a routerLink="/parent/child">Go to child route</a>
```
注意:子级路由的路径是相对于父级路由的路径而言的。在上面的例子中,子级路由的完整路径是 `/parent/child`。如果父级路由的路径是 `/parent/:id`,那么子级路由的完整路径就是 `/parent/:id/child`。