Access Variables/Functions from Another Component

Access variables/functions from another Component

How to access variables/functions from another Class. The variable or function you want to access or called must be public not private.

public class ScriptA : MonoBehaviour{

public int playerScore = 0;

void Start()
{

}

public void doSomething()
{

}
}

Access variable playerScore in ScriptA from ScriptB. First, find the GameObject that the script or component is attached to with the GameObject.Find function then use the GetComponent function to retrieve that script or component that is attached to it.

public class ScriptB : MonoBehaviour{

ScriptA scriptInstance = null;

void Start()
{
GameObject tempObj = GameObject.Find("NameOfGameObjectScriptAIsAttachedTo");
scriptInstance = tempObj.GetComponent<ScriptA>();

//Access playerScore variable from ScriptA
scriptInstance.playerScore = 5;

//Call doSomething() function from ScriptA
scriptInstance.doSomething();
}
}

How to access variables of one component in another component [Angular]

You can create a service to share the data between components,

A new service called, filter-panel.service.ts file with setter() and getter() method,

import { Injectable } from '@angular/core';

@Injectable()
export class FilterPanelService {

filterdata: any[];
constructor() { }

get data(): any{
return this.filterdata;
}

set data(val: any){
this.filterdata = val;
console.log(this.filterdata);
}

}

In filter-panel.component.ts set the value like,

export class FilterPanelComponent implements OnInit {

public activeFilters: string[];
public text: string="hello world";

constructor(public filterPanelService:FilterPanelService) {

this.activeFilters = [
'Provider: CMS',
'Region: All',
'Provider Group:All',
'Provider: CMS',
'Region: All',
'Provider Group: All'
];

this.filterPanelService.data = this.activeFilters;
}

ngOnInit() {}
}

And in filter-bar.component.ts get the value like,

export class FilterBarComponent implements OnInit {
@ViewChild('FilterPanelComponent', {static : false}) filterPanel: FilterPanelComponent;


public values1: string[] = ['Philips'];

public values2: string[];


constructor(public filterPanelService: FilterPanelService) {

//this.values2=this.filterPanel.activeFilters;
}

ngOnInit() {
//console.log(this.values2);
console.log('value received ', this.filterPanelService.data);
}
}

Working Stackblitz..

React.js passing one components variables to another component and vice-versa

It depends on your app's style. If it is a simple app where component two needs to access componenet one's variables props would be easy to use. However, as apps scale, you need to consider situations where component two needs to access a global state. Then, things change. Suppose your ComponentOne is the parent that contains & controls the state and ComponentTwo is the child and will only use the state passed from the parent.

Component1.js

import React from 'react';
import ComponentTwo from "./yourcomponent2directory.js"

const ComponentOne = () => {

varOne = Mike;
varTwo = Tyson;

return
(
<div>
<ComponentTwo varOne={varOne} varTwo={varTwo}/>
</div>
)}

export default ComponentOne

ComponentTwo.js

import React from 'react';
import ComponentOne from '../OtherFolder/';

const ComponentTwo = (props) => {

return(
<div>
<p>{props.varOne}, {props.varTwo}</p>
</div>
)}

export default ComponentTwo

or you can destructure props like...

const ComponentTwo = ({varOne,varTwo}) => {

return(
<div>
<p>{varOne}, {varTwo}</p>
</div>
)}

export default ComponentTwo

React: How can i run a function from another Component with state Variables

Looks like, you want to have a LoginForm Component, and a LoginFormButton to handle form submit.

import React, { Component } from "react";import { Pane, TextInputField, Checkbox, Button } from "evergreen-ui";import { validateEmail, validatePassword } from "./FormValidator";
const LoginFormButton = ({ handleSubmit }) => { return ( <Button appearance="primary" marginLeft={8} marginRight={16} intent="success" onClick={() => handleSubmit()} // or just -> onClick={handleSubmit} > Login </Button> );}
class LoginForm extends Component { constructor(props) { super(props); this.state = { passwordErr: { status: false, value: "" }, emailErr: { status: false, value: "" }, email: "", password: "", CheckBoxchecked: false }; this.handleSubmit = this.handleSubmit.bind(this); this.handleCheckbox = this.handleCheckbox.bind(this); }
handleEmailInput = e => { const email = e.target.value; this.setState({ email: email }); };
handlePasswordInput = e => { const password = e.target.value; this.setState({ password: password }); };
handleCheckbox() { this.setState({ CheckBoxchecked: !this.state.CheckBoxchecked }); }
handleSubmit() { if (this.checkFormStatus()) { alert("Form OK"); } }
checkFormStatus() { // form validation middleware const { email, password } = this.state; const emailErr = validateEmail(email); const passwordErr = validatePassword(password);
if (!emailErr.status && !passwordErr.status) { return true; } else { this.setState({ emailErr, passwordErr }); return false; } }
render() { return ( <Pane padding={15}> <TextInputField tabIndex={0} required isInvalid={this.state.emailErr.status} validationMessage={ this.state.emailErr.status ? this.state.emailErr.value : false } onChange={this.handleEmailInput} value={this.state.email} appearance="neutral" type="email" label="Your email-address" inputHeight={36} //description="We’ll need your email-address to create an new account" /> <TextInputField required validationMessage={ this.state.passwordErr.status ? this.state.passwordErr.value : false } isInvalid={this.state.passwordErr.status} onChange={this.handlePasswordInput} value={this.state.password} appearance="neutral" label="Your Password" type="password" inputHeight={36} //description="Create a secure password to protect your account" /> <Checkbox label="Keep me logged in" checked={this.state.CheckBoxchecked} onChange={this.handleCheckbox} /> <LoginFormButton handleSubmit={this.handleSubmit} /> </Pane> ); }}export default LoginForm;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

How can I read a variable from another component in React?

If you want read variables from another component you can use many ways. It depends how you chain those components.

If the base value is in parent and you want to pass it to child use props https://reactjs.org/docs/components-and-props.html

const element = <Welcome data1 ={valueFilterActive} data2 ={valueFilterName} />;

function Welcome(props) {
return <h1>Hello, {props.valueFilterName} {props.valueFilterActive}</h1>;
}

If the base value is in child and you want to pass it to parent use callback function
https://reactjs.org/docs/faq-functions.html

But if its more complicated way i recommend using Context Hook
https://reactjs.org/docs/hooks-reference.html#usecontext

(PS: Also in react you don`t use getElementById but another hook called useRef
https://reactjs.org/docs/hooks-reference.html#useref)

How to get value of variable from another component, not child?


When using ViewChild with {static: false} the property is available in (and after) the ngAfterViewInit hook

ngAfterViewInit() {
console.log(this.dialogDictionaryTypes.dictionaries);
}

If you really need it in the ngOnInit, you can set static to true, but be aware that if you have any structural directive surrounding your child component, it will fail.

After reading your title, I see that the component you are looking for is -not- a child. In that case you should -always- use a service and inject this service in both components.

ViewChild is only used to obtain a reference of a component or HTMLElement instance declared inside your component's template

Also, your initial thought of accessing data from components is a bit flawed. You should never do this, because components are just used for views and interaction with the view, not for data storage. Try to keep them as dumb as possible.

@Injectable({ providedIn: 'root' })
export class DictonaryService {
readonly dictionaries: Dictionary[] = [];
}

@Component({

})
export class DialogDictionariesTypesComponent {
constructor(private ds: DictionaryService) {}

ngOnInit(): void {
console.log(ds.dictionaries);
}
}


@Component({

})
export class SomeOtherComponent {
constructor(private ds: DictionaryService) {}

ngOnInit(): void {
console.log(ds.dictionaries);
}
}

In this example these components will log the same dictionary array. This is however very rudimentary and you should really look into using data streams using rxjs to make your life easier (maybe even state management). Harder at first, I agree, but once you get the hang of it, your code will be very happy with you.



Related Topics



Leave a reply



Submit