【问题标题】:Setting Angular Component Input Value from the Webpage从网页设置 Angular 组件输入值
【发布时间】:2016-10-12 09:04:53
【问题描述】:

我有一个服务器端渲染页面,我希望能够从网页动态设置 Angular 组件的输入值。

<body>
  <testcmp [testa]="'Blue322'"></testcmp>
</body> 

http://plnkr.co/edit/YoZOnGWI6R1Urj89tJAZ?p=preview

我注意到我只能从模板(我的 plunkr 中的“testb”)设置组件的值,但不能从外部(“testa”)设置。

我需要做什么才能从网页设置“testa”的值?

【问题讨论】:

    标签: angular


    【解决方案1】:

    如果我没记错的话,您不能在应用程序的 ROOT 组件上使用 Input 之类的东西。 看: Angular 2 input parameters on root directive

    https://github.com/angular/angular/issues/1858#issuecomment-151326461

    这不起作用的原因是您的 index.html 在其中 你放置的不是有角度的 零件。因此,Angular 不会编译这个元素。和 Angular 在运行时不读取属性值,仅在 编译时间,否则我们会受到性能影响。

    即这按预期工作,请使用@Mewel 的代码 sn-p 描述...

    【讨论】:

    • Angular 应用程序有没有办法从 index.html 页面获取值?
    • 现在想不出任何办法。但是为什么你在 index.html 中如此需要它呢?
    • 出于 SEO 原因,我的页面是从服务器动态生成的。它实际上是一个 aspx 页面,我希望服务器初始化 Angular 应用程序中的值。
    • 也许尝试创建一个从服务器获取一些参数的服务,然后将该服务注入到 onInit 的根组件中。 (记得实现 onInit 接口)。这就是我会这样做的方式,但请注意我在 ASP.Net 方面没有任何经验
    【解决方案2】:

    我认为正确的方法应该是创建 Angular 应用程序并在应用程序内部使用组件。

    您不应该直接在 index.html 页面上使用组件,您应该在引导应用程序之前。

    编辑:你可以试试这个解决方法

    <testcmp testa="Blue322"></testcmp>
    
    import {Component, Input, ElementRef} from 'angular2/core';
    ...
    export class TestCmp {
        testa: string;
    
        constructor(public elementRef: ElementRef) {
        }
    
        ngOnInit(){
          this.testa = this.elementRef.nativeElement.getAttribute('testa');
        }
    }
    

    【讨论】:

    • Angular 应用程序有没有办法从 index.html 页面获取值?我的页面实际上是一个aspx页面,其内容是从服务器动态生成的。我想允许此页面在 Angular 应用程序中设置值。
    • 我用代码编辑答案以让应用程序工作并读取标签,我认为没有办法使用 angular @Input 来处理这个问题。
    • 成功了。谢谢。我避免了这种情况,因为我在某处读到使用输入更可取,但如果无法使用输入,那就这样吧。
    • 使用@Input 是不可能的,因为 index.html 没有被解释为角度组件并且框架不会编译它,我认为这是实现你需要的唯一方法。不客气:)
    猜你喜欢
    • 2014-08-06
    • 1970-01-01
    • 2018-09-07
    • 2016-11-16
    • 2016-04-19
    • 2020-10-08
    • 2021-11-09
    • 2020-04-22
    • 1970-01-01
    相关资源
    最近更新 更多