首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在angular 8中将div id从一个组件访问到另一个组件

在Angular 8中,可以通过使用@ViewChild装饰器来访问一个组件中的div id,并在另一个组件中使用。

首先,在要访问div id的组件中,给该div添加一个模板引用变量。例如,给div添加一个id为"myDiv"的模板引用变量,可以这样写:

代码语言:txt
复制
<div #myDiv></div>

然后,在要访问该div的组件的.ts文件中,使用@ViewChild装饰器来获取对该div的引用。在组件的类中添加以下代码:

代码语言:txt
复制
import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent {
  @ViewChild('myDiv', { static: true }) myDiv: ElementRef;

  // 在需要访问div的地方使用this.myDiv.nativeElement
}

现在,你可以在该组件的代码中使用this.myDiv.nativeElement来访问该div。

接下来,在另一个组件中,你可以通过在构造函数中注入要访问的组件,然后使用该组件的实例来访问该div。例如:

代码语言:txt
复制
import { Component } from '@angular/core';
import { YourComponent } from '../your-component/your-component.component';

@Component({
  selector: 'app-another-component',
  templateUrl: './another-component.component.html',
  styleUrls: ['./another-component.component.css']
})
export class AnotherComponent {
  constructor(private yourComponent: YourComponent) {
    // 在构造函数中注入YourComponent组件
  }

  // 在需要访问div的地方使用this.yourComponent.myDiv.nativeElement
}

现在,你可以在另一个组件中使用this.yourComponent.myDiv.nativeElement来访问第一个组件中的div。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

  • Angular系列教程-第五节

    1.模块 NgModule 是一个带有 @NgModule 装饰器的类。 @NgModule 的参数是一个元数据对象,用于描述如何编译组件的模板,以及如何在运行时创建注入器。 它会标出该模块自己的组件、指令和管道,通过 exports 属性公开其中的一部分,以便外部组件使用它们。 NgModule 还能把一些服务提供商添加到应用的依赖注入器中。 NgModule 的元数据会做这些: 声明某些组件、指令和管道属于这个模块。 公开其中的部分组件、指令和管道,以便其它模块中的组件模板中可以使用它们。 导入其它带有组件、指令和管道的模块,这些模块中的元件都是本模块所需的。 提供一些供应用中的其它组件使用的服务。 每个 Angular 应用都至少有一个模块,也就是根模块。 你可以引导那个模块,以启动该应用。

    02
    领券