【发布时间】:2020-11-08 15:34:19
【问题描述】:
我正在构建一个 Angular 库(让我们将其视为“mylib”)。在这个库中,我只使用了 mylib.component.ts 文件。我在这个文件的模板变量中添加了 html 元素代码。用于对这些 html 元素进行修改的函数也在同一个 component.ts 文件中。我成功构建并发布到 npm。但是当我尝试在一个新项目中安装和使用它时,它说这样的功能不存在。我做错了什么?我想知道的是,如何访问在 Angular 库的 component.ts 中声明的函数。如果不能,那么在另一个项目中安装这个库后,我应该怎么做才能访问这些功能?
mylib.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'srr-mylib',
template: `
<h1> Random Text </h1>
`,
styles: [
]
})
export class ElapsedtimerComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
startTrans(){
//some code here
}
}
mylib.module.ts
import { NgModule } from '@angular/core';
import { MylibComponent } from './mylib.component';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
declarations: [MylibComponent],
imports: [
CommonModule,
BrowserModule
],
exports: [MylibComponent]
})
export class MylibModule { }
public.api.ts
/*
* Public API Surface of mylib
*/
export * from './lib/mylib.service';
export * from './lib/mylib.component';
export * from './lib/mylib.module';
这就是我尝试在新项目中使用上述库的方式
app.component.html
<srr-mylib></srr-mylib>
app.component.ts
import { Component } from '@angular/core';
import { MylibModule } from '@somename/mylib'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(
private libz:MylibModule
) {
libz.startTrans() //<----- this doesn't work. it gives the error as "Property 'startTrans' does not exist on type 'MylibModule'.ts(2339)"
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MylibModule } from '@somename/mylib'
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
MylibModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
【问题讨论】:
-
永远不要在构造函数中注入模块。您应该尝试使用
@ViewChild来获取 HTML 中的组件。但这是一种反模式,你应该找到另一种改变颜色的方法(一个公共服务,或者你的 lib 组件中的 @Input ......) -
@Random 实际上没有 changeColour 不是一个实际的函数。我的意图也不是改变颜色。我只是在这里使用该函数名称作为示例。我只想知道如何访问库的 component.ts 文件中声明的函数
-
方法“changeColor”的内容应该与我所说的无关。你能给出一个函数的真实例子吗?该函数是否返回一些东西?函数对组件本身有影响吗?
-
@Random 有很多功能。现在让我们考虑一个更改“模板”中某个 html 元素的字体大小的函数。这是函数
document.getElementById('timer').style.fontSize = fontSize+'px';中的代码我知道你可以使用Input() 来做到这一点。但我需要使用函数以编程方式执行此操作。因为我也需要对其他功能应用相同的逻辑。那些所说的功能不会返回任何东西。他们只是修改 html 元素。
标签: angular typescript angular-library