【问题标题】:angular - How to access functions declared inside component.ts of an angular library?angular - 如何访问在 Angular 库的 component.ts 中声明的函数?
【发布时间】: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


【解决方案1】:

在 Angular 中,组件不应直接调用其他组件的方法。因此,根据我对您尝试做的事情的理解,我会改用@Input,它会触发函数调用:

mylib.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'srr-mylib',
  template: `
    <h1 [ngStyle]="{'font-size': myFontSize}"> Random Text </h1>
    <button type="button" (click)="onClickPlusFontSize()">Larger font size</button>
  `,
  styles: [
  ]
})
export class ElapsedtimerComponent implements OnInit, OnChanges {

  @Input() inputFontSize: number;
  @Output() inputFontSizeChange: EventEmitter<number> = EventEmitter();

  public myFontSize: string;

  constructor() {
  }

  ngOnInit(): void {
  }


  ngOnChanges(changes: SimpleChanges): void {
    if (changes.inputFontSize) {
      // triggered every time the @Input value changes
      this.onFontSizeChange(changes.inputFontSize.currentValue);
    }
  }

  onFontSizeChange(newFontSize) {
    this.myFontSize = `${newFontSize}px`;
    // some other stuff
  }

  onClickPlusFontSize() {
    this.inputFontSize++; // updates the value
    onFontSizeChange(this.inputFontSize); // triggers the function that should be called, as if the change came from the parent
    this.inputFontSizeChange.emit(this.inputFontSize) // tells the parent that the value changed
  }
}

app.component.html

<srr-mylib [(inputFontSize)]="myLibFontSize" (inputFontSizeChange)="onFontSizeChange($event)"></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 {
  public myLibFontSize: number;

  constructor() {
    this.myLibFontSize = 12; // will trigger ngOnChanges on myLib
  }

  onSpecificEvent() {
    // do stuff
    this.myLibFontSize = 20; // will also trigger ngOnChanges on myLib
  }
 
  onFontSizeChange(newFontSize: number) {
    // this method is optionnal.
    // with '[(inputFontSize)]="myLibFontSize"' in the HTML, the value of 'myLibFontSize' will already be updated automatically.
    // this function is only useful if the parent wants to do specific work when the value changes.
    // so there is absolutely no need to do "this.myLibFontSize = newFontSize" here.
    // the only thing to know, is that you have no clue of either 'myLibFontSize' will be updated after of before 'onFontSizeChange' is called.
    // So always use 'newFontSize' in this method, to be sure of the value used.
    console.log('myLibFontSize value changed !', newFontSize);
  }

}

【讨论】:

  • 感谢您的支持!假设在 html 元素中有一个计数器,可以使用那里的向上和向下按钮更改值。如果我编写一个函数来返回该计数器的当前值,那么在使用该库时如何访问该函数?
  • @SankhaRathnayake 对于这个,你可以使用“双向绑定”,看我的编辑
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-29
  • 2019-02-08
  • 1970-01-01
  • 2019-12-26
相关资源
最近更新 更多