【问题标题】:Angular: Setting component property outside of the componentAngular:在组件之外设置组件属性
【发布时间】:2019-02-20 12:57:59
【问题描述】:

我有一个 Angular 页面,它使用一个组件来显示它的一些属性。但是组件的属性不会显示在页面上。代码如下:

HTML 页面 (testPage.component.html)

<p>title: {{title}}</p>
<p>another title: {{anotherTitle}}</p>

TypeScript (testPage.component.ts)

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

@Component({
  selector: 'app-testPage',
  templateUrl: './testPage.component.html',
  styleUrls: ['./testPage.component.css']
})
export class TestPageComponent implements OnInit {
  title: string;
  anotherTitle = "This is another title";

  setTitle(): void {
    this.title = "This is title!!";
    console.log('This is title', this.title);
  }
}

var testPageComponent = new TestPageComponent();
//newBudgetComponent.title = "some title here!!"; //Also not working
testPageComponent.setTitle();

在页面中,anotherTitle 填充得很好,但 title 没有填充。

函数 setTitle 记录标题,但 Angular 页面不显示该值。

这是页面的外观:

如何在组件外设置组件属性?

【问题讨论】:

  • 你到底想在这里实现什么?
  • 请分享用例。可能有几种方法可以做到这一点,但归根结底,您为什么要尝试从应用程序外部设置值?

标签: angular typescript components


【解决方案1】:

您是否要设置页面标题?如果是,则使用 Title 服务

import { Title } from '@angular/platform-browser';

constructor(private titleService: Title)

this.titleService.setTitle("Title");

否则使用带有行为主题的共享服务,除非它是子组件然后使用输入

【讨论】:

    【解决方案2】:

    有几种方法可以实现这一点。首先,Angular 中组件的交互以及它们在页面上的显示方式比您尝试展示的示例要简单一些。请参考this link 了解更多关于 Angular 中组件生命周期的信息。

    至于设置组件的属性值,这里有几个例子。请记住,其中一些可能需要调整,因为我没有在 IDE 中编写/运行代码。

    您的示例已经这样做了。创建组件时,该字段的默认值已设置。 title = 'My Title'

    使用@Input() 装饰您的属性允许您将数据从父组件传递到子组件。 &lt;my-child-component [title]='value-or-variable'&gt;&lt;/my-child-component&gt;

    使用@ViewChild() 装饰器装饰“组件”属性(在这种情况下是父组件中的子组件)将允许父组件访问子组件并使用它的属性。请记住,指示的组件必须是父组件的子组件。 @ViewChild(MyChildComponent) child: MyChildComponent; 然后在父组件的初始化循环完成后this.child.title = 'My Title';

    使用 @ContentChild() 装饰器装饰“组件”属性(在这种情况下是父组件或任何后代中的子组件)将允许父组件访问后代组件并使用它们的后代和属性。请记住,指示的组件可以是此父级的任何后代组件。 @ContentChild(MyDescendentComponent) descendent: MyDescendentComponent; 然后在初始化周期完成后 this.descendent.title = 'My Title';

    提供的对象可以被注入到组件中,并在 ngOnInit 方法中为组件设置值。提供者可以设置在几个不同的级别,包括(但不限于)组件模块。 This link 对依赖注入的深入程度更高,尽管它稍早一些。

    class MyComponent {
      constructor(myService: MyService) {}
    }
    
    //module
    providers: [
      MyTitleToken,
    ],
    
    //component
    class MyComponent {
      constructor(public title: MyTitleToken) {}
    }
    
    //module
    providers: [
      {provide: 'MyTitle', useValue: 'Hello Title'},
    ],
    
    //component
    class MyComponent {
      constructor(@Inject('MyTitle') title: string) {}
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 2019-03-24
      • 2019-05-05
      • 2021-10-29
      • 1970-01-01
      • 2019-04-20
      • 2016-11-07
      • 2020-05-06
      • 2019-10-20
      相关资源
      最近更新 更多