簡體   English   中英

從Angular2中的AppComponent將參數傳遞給子組件或對等組件

[英]Passing parameter to child or peer component from AppComponent in Angular2

我在Angular2上的NativeScript TypeScript中有一個應用程序,由AppComponent和LoginComponent組成,該應用程序是通過Playground Web應用程序通過拖放創建的,用於NativeScript。 我想將AppName變量從AppComponent傳遞到LoginComponent,但這樣做沒有任何運氣。 我看過示例,但是它們引用了模板,而本示例中的模板沒有引用外部變量。 該參數僅在組件之間傳遞。

出現登錄屏幕,除了傳遞applicationName之外,其他一切正常。 我不確定自己想念的是什么。

這不是父母/子女關系嗎? 我找不到任何可以表明它是否基於聲明塊描述的信息。 如果不是,則是用於在對等組件之間傳遞參數的備用機制。

任何幫助,將不勝感激。

AppComponent如下所示:

import ...

@Component({
    selector: "ns-app",
    templateUrl: "app.component.html"
})
export class AppComponent implements OnInit
{
    applicationName: string = "APP NAME";

    constructor(private routerExtensions: RouterExtensions)
    {
    }
}

LoginComponent的相關部分是:

import { Component, ElementRef, Input} from "@angular/core";
import ...

@Component({
    selector: "app-login",
    moduleId: module.id,
    templateUrl: "./login.component.html",
    styleUrls: ['./login.component.css']
})
export class LoginComponent
{
    @Input() applicationName: string;

    ...

    alert(message: string)
    {
        return alert({
            title: this.applicationName,
            okButtonText: "OK",
            message: message
        });
    }
}

這兩個組件都在NgModule定義中引用

@NgModule({
    bootstrap: [
        AppComponent
    ],
    imports: [
        AppRoutingModule,
        NativeScriptCommonModule,
        NativeScriptModule,
        ...
    ],
    declarations: [
        AppComponent,
        LoginComponent
    ],
    schemas: [
        NO_ERRORS_SCHEMA
    ]
})
export class AppModule { }

app-routing.module.js文件包含

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var router_1 = require("nativescript-angular/router");
var login_component_1 = require("./login/login.component");
exports.routes = [
    { path: "", redirectTo: "/login", pathMatch: "full" },
    { path: "login", component: login_component_1.LoginComponent },
    { path: "home", loadChildren: "./home/home.module#HomeModule" },
    ...
];
var AppRoutingModule = /** @class */ (function () {
    function AppRoutingModule() {
    }
    AppRoutingModule = __decorate([
        core_1.NgModule({
            imports: [router_1.NativeScriptRouterModule.forRoot(exports.routes)],
            exports: [router_1.NativeScriptRouterModule]
        })
    ], AppRoutingModule);
    return AppRoutingModule;
}());
exports.AppRoutingModule = AppRoutingModule;

由於要從路由器加載LoginComponent ,因此不能使用@Input傳遞數據。 嘗試在Routes本身中注入data或使用可以注入任何組件並共享數據的服務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM